CSS 기초 정리

ㅎㅎ·2021년 4월 1일
0

HTML/CSS

목록 보기
2/5


: Code Academy CSS 정리


📌 CSS?

: Cascading Style Sheets is a language that web developers use to style the HTML content on a web page

SETUP

  • Inline Styles - To style an HTML element, you can add the style attribute directly to the opening tag
  • <style> - it must be placed inside of the <head>element.
<head>
  <style>
    p {
      color: red;
      font-size: 20px;
    }
  </style>
</head>
  • linking the css file -
    • href is for address, path, css file,
    • type - The value of this attribute should be set to text/css.
    • rel - html과 css의 관계를 나타냄. the value should be set to stylesheet.
<link href="https://www.codecademy.com/stylesheets/style.css" type="text/css" rel="stylesheet">

<!-- in same directory-->
<link href="./style.css" type="text/css" rel="stylesheet">

SELECTORS(선택자)

  • CSS can select HTML elements by tag, class, or ID.
  • class - css에서 사용하기 위해서는 .을 앞에 붙여야함.
<!-- in HTML -->
<p class="brand">Sole Shoe Company</p>

<!-- in CSS -->
.brand {
  color: teal;
}
  • mutiple class도 가능.
<!-- html -->
<h1 class="green bold"> ... </h1>
<!-- CSS -->
.green {
  color: green;
}
 
.bold {
  font-weight: bold;
}
  • id - css에서 사용하기 위해서 #을 앞에 붙여야함.
<h1 id="large-title"> ... </h1>
#large-title {
	color:gray; 
}
  • CSS classes are meant to be reused over many elements but, an ID is meant to style only one element.

  • Multiple selectors - 서로 다른 element를 묶는 것도 가능. refer to as chaining. The code would select only the h1 elements that have a class of "special".

h1.special {
 
}
  • Nested Elements - Nested elements can be selected by separating selectors with a space(띄어쓰기 꼭). element 안의 element을 가져올 때, <ul>안의 <li>를 가져옴. 이때 <li> 만 바뀜.
<ul class='main-list'>
  <li> ... </li>
  <li> ... </li>
  <li> ... </li>
</ul>
.main-list li {
 
}
  • Multiple (unrelated) Selectors : This prevents writing repetitive code.
h1, 
.menu {
  font-family: Georgia;
}

SPECIFICITY(우선순위)

  • Specificity is the order by which the browser decides which CSS styles will be displayed
  • id - class - tags
  • Adding more than one tag, class, or ID to a CSS selector increases the specificity of the CSS selector. 밑의 코드가 더 우선순위가 높음.
p {
  color: blue;
}
 
 
.main p {
  color: red;
}

VISUAL RULES

  • In code,color: blue, this line is referred to as a CSS declaration. CSS declarations consist of a property and a value.
    • Property(속성) — the property you’d like to style of that element (i.e., size, color, etc.).
    • Value(값) — the value of the property (i.e., 18px for size, blue for color, etc.).
h1 {
  color: blue;
}
  • font-family: 서체 , font-size :폰트크기(px) , font-weight - bold, normal
  • text-align-center, left, right
  • background-color: 배경 색 , color: the color of the text, opacity:투명도
  • background-image:
.main-banner {
  background-image: url("https://www.example.com/image.jpg");
}
  • !important : 무조건 먼저, it will override any style no matter how specific it is. (그러나 사용하지 않는게 좋음)
p {
  color: blue !important;
}

THE BOX MODEL

  • 요소: width and height , padding, border, margin
  • Resetting Defaults: user agent stylesheets에는 기본값을 설정하는 기본 css규칙이 있는데 이는 개발자가 스타일링을 하는것을 어렵게 함. 따라서 이 규칙들을 reset하는 방법이 존재함.
* {
  margin: 0;
  padding: 0;
}
  • visibility :this property can hide or show elements.
    • visible, hidden
      (이때 hidden 과 display:none과의 차이점은 hidden은 사용자에게 보이지는 않지만 공간은 유지된다.)
.future {
  visibility: hidden;
}

- width, height

  • min-width, max-width, min-height, max-height: 디스플레이마다의 크기 변화를 막기 위해, 너비와 높이의 최대,최소가 존재.

- padding

: content와 border 사이의 공간크기를 지정함.

  • padding-top ,padding-right ,padding-bottom
    padding-left
p.content-header {
  border: 3px solid grey;
  padding: 6px 11px 4px 9px; 
  <!-- 위 오 아래 왼 순으로  --> 
}

p.content-header {
<!--위아래, 오왼이 같을 때 -->
  padding: 5px 10px;
}

- border

: padding을 둘러싼 border의 스타일과 두께를 지정함. 프레임같이(테두리).

  • width : border의 두께 (thin, medium, thick)
  • color : 색상표 참고
  • style : 다양한 스타일 참고 (none, dotted, solid ... )
  • border-radis : 모서리모양을 바꿀 수 있음. 만약, 완벽한 원형을 만들고 싶다면 너비와 높이를 동일하게하고, 50px으로 설정하기.
p {
  border: 3px solid coral;
}

div.container {
  border: 3px solid rgb(22, 77, 100);
  border-radius: 5px;
}

- margin

: border과 그 밖의 요소 사이의 공간크기를 지정함. 즉 박스 밖의 공간을 말함.

  • margin-top,margin-right,margin-bottom
    margin-left
  • auto : 밑의 코드에서 0은 위와 top과 bottom을 0으로, auto는 왼쪽과 오른쪽의 정 가운데로 맞추기위해서 조정해준다. (요소의 중심을 맞추려면 width가 필수)
div {
  margin: 0 auto;
}
p {
<!-- 위 오른 아래 왼 순으로-->
  margin: 6px 10px 5px 12px;
}

p {
<!-- 위아래, 오왼이 같을 때-->
  margin: 6px 12px;
}
  • Margin Collapse(vertical margins) - the space between vertically adjacent elements will equal to the larger margin.
    첫번째 코드라면 두 박스의 total margin은 40px. 두번째 코드라면 margin collapse가 일어나 원래는 50px이 되어야하지만, 더 큰 margin인 30px으로 적용됨.
<!-- 1st -->
#img-one {
  margin-right: 20px;
}
 
#img-two {
  margin-left: 20px;
}

<!-- 2nd -->
#img-one {
  margin-bottom: 30px;
}
 
#img-two {
  margin-top: 20px;
}

- overflow

:it dictates how HTML will render content that overflows its parent’s content area.

  • hidden,scroll :스크롤바가 추가됨,visible: 디폴트
p {
  overflow: scroll; 
}

CHANGING THE BOX MODEL

  • the box dimensions are affected by 'border thickness' and 'padding .

  • The box-sizing property controls the box model used by the browser.

    • content-box: 디폴트. width를 설정했을 때, padding과 border을 포함해서 계산함.
      이때 width는 width + padding-left + padding-right + border-left + border-right를 말함.

    • border-box: 위의 width에서 padding과 border이 제외된다. 즉, width 120px, padding:20p. border:5px라면 , width를 기준으로 안쪽에 padding과 border이 생김.

* {
  box-sizing: border-box;
}
  • 위의 코드에서 *는 모든 elemens를 가르키고, 박스모델을border-box로 바꾸는 것을 뜻함.

DISPLAY AND POSITIONING(레이아웃)

- Display

  • values: inline.block.inline-block
  • inline : 말 그래도 같은 라인, 요소 옆에 다른 요소 붙일 수 있음. 인라인 태그들은 오직 자신들의 내용만을 감싸므로 새로운 라인을 필요로 하지 않음.

    ex) <span>,<em>,<strong>,<a> , inline 태그 목록

  • block : 이 요소 바로 옆은 다른 요소를 붙일 수 없음. 즉 전체 너비들 다 가진다. width로 조절 가능함.
    ex) <h1>~<h6>,<p>,<div>,<footer>,,, block-display 태그 목록

  • inline-block : 위의 두개를 합친 것. 두 개의 element를 나란히 배치할 수 있으며, 그 크기를 width와 height를 통해 조절가능함.

➡️ 이 때 알아야 할 점은, display inline 성질을 가진 태그도 block으로, block성질을 가는 태그도 inline 태그로 display, float 속성을 이용해 바꿀 수 있다.

.inline-p {
  display: inline-block;
}
.float-left {
  float: left;
}
.float-right {
  float: right;
}


.block-span {
  display: block;
}


- Position

: html 코드와 상관없이 어느 위치에나 요소를 그릴 수 있음.

  • values: static,relative,absolute,fixed
  • static: 디폴트, block-level에서 왼쪽으로 치우쳐있다. 거의 사용하지않음.

  • relative: 그 자체로는 특별한 의미가 없음. top,bottom,left,right 와 같은 offset 속성들이 있어야 원래의 위치에서 이동할 수 있음.

.relative {
  position: relative;
}
.top-20 {
  top: -20px;
  left: 30px;
}

➡️ 위의 코드라면 .relative가 position이 relative이므로 저 셀렉터를 가질때는 위로 20px만큼 이동하고, 왼쪽에서 30px만큼 떨어진다. 이 때 마이너스 값을 주면 아래로 떨어지지 않고 위로 올라간다.

  • absolute: 이름과 같이 절대적인 위치에 놓을 수 있음. 즉 부모에 대해 절대적으로 움직인단는 의미. 부모 중에 positinodl relative, fixed, absolute 중 하나라도 있으면 그 부모에 대해 절대적으로 움직인다. 일반적으로는 absolute를 쓸 경우네는 부모에 position:relative를 부여함. 그리고 offset 속성들이 존재하지 않으면 가까운 element를 덮음.
p {
  margin: 0;
  background-color: yellow;
}
.absolute {
  position: absolute;
}
.right-0 {
  right: 0; 
  bottom: 0;
}

➡️ p 태그는 block- element이기 때문에 가로 크기가 부모 너비만큼 차지하는데, inline-element 크기 만큼 너비가 생김. 이유는 absolute 값을 갖게 되면 내용의 크기만큼만 가로를 갖게 된다.

  • fixed :스크롤하는 것과 상관없이 화면에 고정됨. 즉 눈에 보이는 브라우저 화면 크기만큼 화면 내에서만 움직인다.


- Z-index

  • this property controls how far “back” or how far “forward” an element should appear on the web page when elements overlap. 즉 우선순위.
  • integer value를 가짐. 코드를 보면 top이 2로 더 높기 때문에, 앞으로 감. 기본 디폴트는 0.
.box-top {
  background-color: Aquamarine;
  position: relative;
  z-index: 2;
}
 
.box-bottom {
  background-color: DeepSkyBlue;
  position: absolute;
  top: 20px;
  left: 50px;
  z-index: 1;
}

- float

: 내가 원하는 만큼 오른쪽이나, 원쪽으로 옮길 수 있음.

  • values: left,right, none
  • 사용 시 width가 정확히 명시되어야함. 그렇지 않으면, 플로트를 변경해도 결과가 제대로 보이지 않음.
  • float 속성을 가진 요소는 부모의 높이를 인지를 못해서 자식 요소가 부모 요소를 벗어난다.

➡️ 해결 방법

  1. 바깥 div에 hidden 속성 주기
.box{
	overflow:hidden;
}
  1. 바깥 div를 float 시키기. 이렇게 하면 자식이 float 높이를 인지해 바깥 div만큼의 높이를 차지하게 된다. 하지만 이때 float이 되어서 block성질이 사라지게 때문에 width: 100%를 적용시켜야한다.

- clear

: float가 자식 요소가 부모 요소를 벗어나는 문제를 해결가능하게 해주는 또 다른 방법.

  • values:
    • left: 왼쪽에 float가 지정된 요소들을 해제.
    • right : 오른쪽에 float가 지정된 요소들을 해제.
    • both : 얖 옆에 float가 지정된 요소들을 해제.
    • none: 디폴트.

COLORS

  1. Named colors : 147개의 named color가 존재.
  2. Hexademimal or hex colors(16진수) - it is a number system with has 16 diits, 0 to 9 부터 "A" to "F". #으로 시작하고 빨, 파, 초의 색을 16진수로 표현 ex) #23F41A
  3. RGB : this colors use the rgb() syntax with one value for red, one value for blue, one value for green and this values range from 0 to 255. ex) rgb(7, 210, 50)
  4. HSL : hue(색조), saturation(채도), lightness(명도)를 의미함. Hue는 범위를 0 부터 360 으로 표현하고, saturation과 lightness는 퍼센트로 표현 ex)hsl(200, 20%, 50%).
  • RGB와 HSL에 추가적으로 네번째 value인 ,a,opacity(불투명도)를 추가 가능함. 이때 퍼센트로 표현. ex) hsla(200,20%,50%,10%)

TYPOGRAPHY

: its the art of arranging text on a page. 즉 서체의 배열.

  • font-family : type of font.
  • font-weight : bold, normal(디폴트) or 숫자로 조절 두께 조절 가능(100 ~ 900까지 , 100단위로)
  • font-style : italic
  • wordp-spacing : 단어! 사이의 간격 지정하기. 디폴트는 0.25em으로 normal. 하지만, 만약에 밑의 코드처럼 0,3em이 주어진다면, 총 word-spacing이 0.55em이 된다.
h1 {
  word-spacing: 0.3em;
}
  • letter-spacing : tracking이란? 글자 사이의 간격을 조절하는 것. 이 tracking을 letter-spacing으로 조절해 글자의 가독성을 높일 수 있음.
  • text-transformation : 대,소문자로 바꾸기. upeercase, lowercase
  • text-align : 정렬하기. right, center, left
  • lint-height : 텍스트 크기를 높이면 두 라인 사이의 공간이 작아지기 때문에, 이때 가독성을 높이기 위해 사용.
    • 1.2 같은 단위없는 숫자(unitless number)는 글꼴 크기의 비율로 계산함.
    • 단위가 붙어 있는 숫자들 ex) px,%,em 은 다 유효함.
    • 만약에 텍스트 크기가 바뀐다면, 단위없는 숫자는 자동으로 크기가 조정되지만, 단위가 붙어 있는 숫자들은 변화없이 고정된다.
p {
  line-height: 1.4;
}

  • fallback fonts : 만약에 폰트가 유저의 컴퓨터에 설치되어 있지 않다면, 그 때 기본적으로 컴퓨터에 설치되어 있는 폰트를 사용하는데 이것을 fallback font라고함. 즉, 밑의 코드는 "Garamond"를 기본적으로 사용하는데 만약에, 없으면 "Times", 또 없으면 serif를 사용하라는 뜻.
h1 {
  font-family: "Garamond", "Times", serif;
}

linking font

: 외부의 폰트를 연결해 사용하는 것.
1. Google Font

    • <head>``</head> 사이에 <link>를 넣어 사이트에서 가져온 주소를 첨부.
<!-- 폰트 하나 연결 -->
<head>
  <link href="https://fonts.googleapis.com/css2?family=Open+Sans" rel="stylesheet">
</head>

<!-- 두개 이상의 폰트도 가능 -->
<head>
  <link href="https://fonts.googleapis.com/css2?family=Open+Sans&family=Playfair+Display" rel="stylesheet">
</head>

@Font-Face

  1. 위의 폰트의 경우, 링크를 브라우저에 검색.
    ex) https://fonts.googleapis.com/css2?family=Open+Sans&family=Playfair+Display
  2. @font-face 부터 끝까지 복사해서 첨부.
@font-face {
  font-family: 'Space Mono';
  font-style: normal;
  font-weight: 400;
  src: local('Space Mono'), local('SpaceMono-Regular'), url(https://fonts.gstatic.com/s/spacemono/v1/adVweg3BJhE6r8jYmXseHQzyDMXhdD8sAj6OAJTFsBI.woff2) format('woff2');
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;
}
  • 추가적으로, 외부 폰트 말고 local font file를 사용하기 위해 @font-face를 사용할 수도 있음. 위와 아래의 코드가 다른점은 밑의 코드는 local주소를 사용했다는 점. 그리고 어떤 폰트 형식을 사용할지 정하기 위해 format을 사용했다는 점.
@font-face {
  font-family: "Roboto";
  src: url(fonts/Roboto.woff2) format('woff2'),
       url(fonts/Roboto.woff) format('woff'),
       url(fonts/Roboto.tff) format('truetype');
}

TRANSITIONS

  • 애니메이션 효과 , 목록
    • duration : 지속기간. s,ms와 같은 시간단위로 설정
      ex) 100ms, 1s
    • delay : 딜레이되는 시간.
    • timing : ease-in,ease-out,ease-in-out,linear
transition-property: color;
transition-duration: 1.5s;
transition-timing-function: linear;
transition-delay: 0.5s;

<!-- 위와 같은 코드 -->
transition: color 1.5s linear 0.5s;
    • 다수의 효과를 주는 것도 가능. 꼭 ,를 써주고 마지막에 ;를 써워야함.
transition: color 1s linear,
font-size 750ms ease-in 100ms;
    • all :모든 property에 같은 transition 적용.
transition: all 1.5s linear 0.5s;

0개의 댓글