카테고리 없음

CSS 요약: 2.5 - 2.10

sily224 2022. 7. 12. 00:53

Background 관련 프로퍼티는 배경으로 이미지 또는 색상을 정의한다.

자세한 내용은 CSS Background and Borders를 참조한다.

1. background-image 프로퍼티

요소에 배경 이미지를 지정한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background-image: url("http://poiemaweb.com/img/bg/dot.png");
    }
  </style>
</head>
<body>
  <h3>Background Image</h3>
</body>
</html>
 

2. background-repeat 프로퍼티

배경 이미지의 반복을 지정한다. 수직, 수평 또는 수직과 수평 모두의 반복을 지정할 수 있다.

background-repeat 프로퍼티의 기본값이 repeat이기 때문에 반복 출력되어 화면을 채운다.

x축으로만 배경 이미지를 반복할 경우, background-repeat 프로퍼티값에 repeat-x, y축으로만 배경 이미지를 반복할 경우, repeat-y를 설정한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background-image: url("http://poiemaweb.com/img/bg/dot.png");
      background-repeat: repeat-x;
    }
  </style>
</head>
<body>
  <h3>background-repeat: repeat-x;</h3>
</body>
</html>
 

반복 출력을 멈추고 싶은 경우, background-repeat 프로퍼티값에 no-repeat를 설정한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background-image: url("http://poiemaweb.com/img/bg/dot.png");
      background-repeat: no-repeat;
    }
  </style>
</head>
<body>
  <h3>background-repeat: no-repeat;</h3>
</body>
</html>
 

background-image에 복수개의 이미지를 설정할 경우, 먼저 설정된 이미지가 전면에 출력된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background-image: url("http://poiemaweb.com/img/bg/dot.png"), url("http://poiemaweb.com/img/bg/paper.gif");
      background-repeat: no-repeat, repeat;
    }
  </style>
</head>
<body>
  <h3>background-repeat: no-repeat, repeat;</h3>
</body>
</html>
 

3. background-size 프로퍼티

배경 이미지의 사이즈를 지정한다. 

프로퍼티값은 px, %, cover, contain 등을 사용한다.

배경이미지의 width, height를 모두 설정할 수 있다. 이때 첫번째 값은 width, 두번째 값은 height를 의미한다. 하나의 값만을 지정한 경우, 지정한 값은 width를 의미하게 되며 height는 auto로 지정된다.

px값 지정

배경이미지 크기가 지정된 px값 그대로 설정된다. 첫번째 값은 width, 두번째 값은 height를 의미한다.

.bg {
  background-size: 700px 500px;
}
 

%값 지정

배경이미지 크기가 지정된 %값에 비례하여 설정된다. 첫번째 값은 width, 두번째 값은 height를 의미한다.

화면을 줄이거나 늘리면 배경이미지의 크기도 따라서 변경되어 찌그러지는 현상이 나타난다.

.bg {
  background-size: 100% 100%;
}
 

cover 지정

배경이미지의 크기 비율을 유지한 상태에서 부모 요소의 width, height 중 큰값에 배경이미지를 맞춘다. 따라서 이미지의 일부가 보이지 않을 수 있다.

.bg {
  background-size: cover;
}
 

4. contain 지정

배경이미지의 크기 비율을 유지한 상태에서 부모 요소의 영역에 배경이미지가 보이지 않는 부분없이 전체가 들어갈 수 있도록 이미지 스케일을 조정한다.

.bg {
  background-size: contain;
}

 

width, height의 프로퍼티값은 공백으로 구분하여야 한다. 프로퍼티값을 쉼표로 구분하면 다른 배경이미지의 너비를 지정하는 것으로 인식되기 때문에 주의가 필요하다.

body {
  background-image: url("front.png"), url("back.png");
  background-repeat: no-repeat, no-repeat;
  background-size: 100%, 500px;
}

4. background-attachment 프로퍼티

일반적으로 화면을 스크롤하면 배경 이미지도 함께 스크롤된다. 화면이 스크롤되더라도 배경이미지는 스크롤되지 않고 고정되어 있게 하려면 background-attachment 프로퍼티에 fixed 키워드를 지정한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    *, *:after, *:before {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    html, body {
      width:100%;
      height:100%;
    }

    .bg-wrap {
      /* page-wrap 보다 bg-wrap이 작은 경우, page-wrap이 가리는 문제를 해결 */
      min-height: 600px;
      height: 100%;
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      /* 마진 상쇄 문제 해결을 위한 코드
        https://developer.mozilla.org/ko/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing
      */
      overflow: auto;
      /* or padding: 0.1px; */
    }

    .parallax {
      background-image: url("http://poiemaweb.com/img/bg/stock-photo-125979219.jpg");
      /* parallax scrolling effect */
      background-attachment: fixed;
    }

    .normal {
      background-image: url("http://poiemaweb.com/img/bg/stock-photo-155153867.jpg");
    }

    #page-wrap {
      width: 400px;
      /* 마진 상쇄 발생 */
      margin: 50px auto;
      padding: 30px;
      background: white;
      box-shadow: 0 0 20px black;
      /* size/line-height | family */
      font: 15px/2 Georgia, Serif;
    }
  </style>
</head>
<body>
  <div class="bg-wrap parallax">
    <div id="page-wrap">
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid ipsum maxime libero, impedit necessitatibus quas blanditiis tenetur vero aut esse unde ab similique, delectus placeat enim quae expedita excepturi laboriosam.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid ipsum maxime libero, impedit necessitatibus quas blanditiis tenetur vero aut esse unde ab similique, delectus placeat enim quae expedita excepturi laboriosam.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid ipsum maxime libero, impedit necessitatibus quas blanditiis tenetur vero aut esse unde ab similique, delectus placeat enim quae expedita excepturi laboriosam.</p>
    </div>
  </div>
  <div class="bg-wrap normal"></div>
</body>
</html>
 

5. background-position 프로퍼티

일반적으로 background-image는 좌상단부터 이미지를 출력한다. 이때 background-position 프로퍼티를 사용하면 이미지의 좌표(xpos, ypos)를 지정 할 수 있다.

기본값은 background-position: 0% 0%;로 배경이미지는 좌측 상단에 위치하게 된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      margin: 0;
    }
    div {
      background-image: url("http://poiemaweb.com/img/bg/dot.png");
      background-color: #FFEE99;
      background-repeat: no-repeat;
      width: 32vw;
      height: 200px;
      margin-bottom: 2vw;
      float: left;
    }
    div:not(:nth-of-type(3n+1)) {
      margin-left: 2vw;
    }
    .example1 {
      background-position: top;
    }
    .example2 {
      background-position: bottom;
    }
    .example3 {
      background-position: center;
    }
    .example4 {
      background-position: left;
    }
    .example5 {
      background-position: right;
    }
    .example6 {
      /* <percentage> values */
      background-position: 25% 75%;
    }
    .example7 {
      /*
        <length> values
        xpos ypos
      */
      background-position: 10px 20px;
    }
    .example8 {
      background-image: url("http://poiemaweb.com/img/bg/dot.png"), url("http://poiemaweb.com/img/bg/dot.png");
      background-position: 0px 0px, center;
    }
  </style>
</head>

<body>
  <div>default(0% 0%)</div>
  <div class="example1">top</div>
  <div class="example2">bottom</div>
  <div class="example3">center</div>
  <div class="example4">left</div>
  <div class="example5">right</div>
  <div class="example6">25% 75%</div>
  <div class="example7">10px 20px</div>
  <div class="example8">0px 0px, center</div>
</body>
</html>
 

6. background-color 프로퍼티

background-color 프로퍼티는 요소의 배경 색상을 지정한다. 색상값 또는 transparent 키워드를 지정할 수 있다.

.bg-col-white {
  background-color: rgb(255, 255, 255);
}

.bg-col-red {
  background-color: red;
}

7. background Shorthand

background-color, background-image, background-repeat, background-position를 한번에 정의하기 위한 Shorthand Syntax이다.

// order
background: color || image || repeat || attachment || position
<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      /* background: color || image || repeat || attachment || position */
      background: #FFEE99 url("http://poiemaweb.com/img/bg/dot.png") no-repeat center;
      width: 50vw;
      height: 300px;
    }
  </style>
</head>
<body>
  <div></div>
</body>
</html>
 

2.7 폰트와 텍스트

 

#1. font-size 프로퍼티

텍스트의 크기를 정의한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .font-size-40 { font-size: 40px; }
    .font-size-2x { font-size: 2.0em; }
    .font-size-150ps { font-size: 150%; }
    .font-size-large { font-size: large; }
  </style>
</head>
<body>
  <p>default font size: 16px</p>
  <p class='font-size-40'>font-size: 40px</p>
  <p class='font-size-2x'>font-size: 2.0em</p>
  <p class='font-size-150ps'>font-size: 150%</p>
  <p class='font-size-large'>font-size: large</p>
</body>
</html>
 

#2. font-family 프로퍼티

폰트를 지정한다. 컴퓨터에 해당 폰트가 설치되어 있지 않으면 적용되지 않는다.

폰트는 여러 개를 동시에 지정이 가능하다. 첫번째 지정한 폰트가 클라이언트 컴퓨터에 설치되어 있지 않은 경우, 다음에 지정된 폰트를 적용한다. 따라서 마지막에 지정하는 폰트는 대부분의 OS에 기본적으로 설치되어 있는 generic-family 폰트(Serif, Sans-serif, Mono space)를 지정하는 것이 일반적이다.

generic-family 폰트

다음은 맥용 크롬 브라우저의 generic-family 폰트 설정 화면이다.

폰트명은 따옴표로 감싸주며 폰트명이 한단어인 경우는 따옴표로 감싸주지 않아도 된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .serif {
      font-family: "Times New Roman", Times, serif;
    }

    .sans-serif {
      font-family: Arial, Helvetica, sans-serif;
    }

    .monospace {
      font-family: "Courier New", Courier, monospace;
    }
  </style>
</head>
<body>
  <h1>font-family</h1>
  <p class="serif">Times New Roman font.</p>
  <p class="sans-serif">Arial font.</p>
  <p class="monospace">Courier New font.</p>
</body>
</html>
 

#3. font-style / font-weight 프로퍼티

font-style 프로퍼티는 이탤릭체의 지정, font-weight 프로퍼티는 폰트 굵기 지정에 사용된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    p { font-size: 2.0em; }

    /*
      font-style
      normal / italic / oblique
    */
    .italic {
      font-style: italic;
    }

    /*
      font-weight
      100 ~ 900 or normal / bold / lighter / bolder
    */
    .light {
      font-weight: lighter;
    }
    .thick {
      font-weight: bold;
    }
    .thicker {
      font-weight: 900;
    }
  </style>
</head>
<body>
  <p>normal style.</p>
  <p class="italic">font-style: italic</p>

  <p class="light">font-weight: lighter</p>
  <p class="thick">font-weight: bold</p>
  <p class="thicker">font-weight: 900</p>
</body>
</html>
 

#4. font Shorthand

Shorthand Syntax

font : font-style(optional) font-variant(optional) font-weight(optional) font-size(mandatory) line-height(optional) font-family(mandatory)
/* size | family */
font: 2em "Open Sans", serif;

/* style | size | family */
font: italic 2em "Open Sans", sans-serif;

/* style | variant | weight | size/line-height | family */
font: italic small-caps bolder 16px/1.2 monospace;

/* style | variant | weight | size/line-height | family */
/* font-variant: small-caps; 소문자를 대문자로 만든다. 단 크기는 일반 대문자에 비해 더 작다.*/
font: italic small-caps bolder 16px/3 cursive;

#5. line-height 프로퍼티

텍스트의 높이를 지정한다. 텍스트 수직 정렬에도 응용되어 사용된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .small {
      line-height: 70%; /* 16px * 70% */
    }
    .big {
      line-height: 1.2; /* 16px * 1.2 */
    }
    .lh-3x {
      line-height: 3.0; /* 16px * 3 */
    }

  </style>
</head>
<body>
  <p>
    default line-height.<br>
    default line-height.<br>
    대부분 브라우저의 default line height는 약 110% ~ 120%.<br>
  </p>

  <p class="small">
    line-height: 70%<br>
    line-height: 70%<br>
  </p>

  <p class="big">
    line-height: 1.2<br>
    line-height: 1.2<br>
  </p>

  <p class="lh-3x">
    line-height: 3.0<br>
    line-height: 3.0<br>
  </p>
</body>
</html>
 

다음은 수직 중앙 정렬 예제이다. a 요소의 line-height 값과 a 요소를 감싸는 div 요소의 height 값을 일치시킨다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .button {
      width: 150px;
      height: 70px;
      background-color: #FF6A00;
      border-radius: 30px;
      box-shadow: 5px 5px 5px #A9A9A9;
    }
    .button > a {
      display: block;
      font: italic bold 2em/70px Arial, Helvetica, sans-serif;
      text-decoration: none;
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="button">
    <a href="#">Click</a>
  </div>
</body>
</html>
 

#6. letter-spacing 프로퍼티

글자 사이의 간격을 지정한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .loose {
      letter-spacing: 2px;
    }
    .tight {
      letter-spacing: -1px;
    }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>

  <p class="loose">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>

  <p class="tight">Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
</body>
</html>
 

#7. text-align 프로퍼티

텍스트의 수평 정렬을 정의한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    h1 { text-align: center; }
    h3 { text-align: right; }
    p.left  { text-align: left; }
    p.justify  { text-align: justify; }
    a  { text-align: center; }
  </style>
</head>
<body>
  <h1>Lorem ipsum</h1>
  <h3>2016.03.07</h3>

  <p class="left">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

  <p class="justify">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

  <a href='#'>Reference</a>
</body>
</html>
 

위 예제의 a 요소에 대한 중앙 정렬은 적용되지 않았다. 이는 a 요소는 inline 요소이기 때문이다. inline 요소는 width 프로퍼티가 없으므로 중앙 개념이 존재하지 않는다. a 요소에 display: block;을 지정한다면 중앙 정렬이 가능할 것이다.

#8. text-decoration 프로퍼티

text-decoration 프로퍼티를 사용하여 링크 underline을 제거할 수 있다. 또는 텍스트에 underline, overline, line-through를 추가할 수도 있다.

<!DOCTYPE html>
<html>
<head>
  <style>
    a { text-decoration: none; }

    p:nth-of-type(1) { text-decoration: overline; }
    p:nth-of-type(2) { text-decoration: line-through; }
    p:nth-of-type(3) { text-decoration: underline; }
  </style>
</head>
<body>
  <a href='#'>text-decoration: none</a>

  <p>text-decoration: overline</p>
  <p>text-decoration: line-through</p>
  <p>text-decoration: underline</p>
</body>
</html>
 

#9. white-space 프로퍼티

white space는 공백(space), 들여쓰기(tab), 줄바꿈(line break)을 의미한다. html은 기본적으로 연속된 공백(space), 들여쓰기(tab)는 1번만 실행되며 줄바꿈(line break)은 무시된다. 또한 텍스트는 부모의 가로 영역을 벗어나지 않고 자동 줄바꿈(wrap)된다. white-space 프로퍼티는 이러한 기본 동작을 제어하기 위한 프로퍼티이다.


프로퍼티값 line break space/tab wrapping(자동줄바꿈)
normal 무시 1번만 반영 O
nowrap 무시 1번만 반영 X
pre 반영 그대로 반영 X
pre-wrap 반영 그대로 반영 O
pre-line 반영 1번만 반영 O
<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      width: 150px;
      height: 150px;
      padding: 10px;
      margin: 40px;
      border-radius: 6px;
      border-color: gray;
      border-style: dotted;
      /*overflow: hidden;*/
    }
    .normal { white-space: normal; }
    .nowrap { white-space: nowrap; }
    .pre    { white-space: pre; }
    .pre-wrap { white-space: pre-wrap; }
    .pre-line { white-space: pre-line; }
  </style>
</head>
<body>
  <h1>white-space</h1>
  <div class="normal"><h3>normal</h3>Lorem   ipsum

    dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
  <div class="nowrap"><h3>nowrap</h3>Lorem   ipsum

    dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
  <div class="pre"><h3>pre</h3>Lorem   ipsum

      dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
  <div class="pre-wrap"><h3>pre-wrap</h3>Lorem   ipsum

    dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
  <div class="pre-line"><h3>pre-line</h3>Lorem   ipsum

    dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
</body>
</html>

https://poiemaweb.com/css3-font-text

 

 

 

아래는 float 대신 inline-block을 사용한 가로 정렬 예제이다.

 

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Infinite looping Crousel Slider</title>
  <style>
    @import url(https://fonts.googleapis.com/css?family=Open+Sans:300,400);

    body {
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      color: #58666e;
      background-color: #f0f3f4;
    }

    .carousel-view {
      /* 자식 컨텐츠 너비에 fit */
      display: inline-block;
      position: relative;
      margin: 0 auto;
      border: 1px dotted red;
    }

    .carousel-container {
      /* 자식 컨텐츠의 줄바꿈을 무시하여 1줄로 가로 정렬한다. */
      white-space: nowrap;
      /* inline-block 레벨 요소 뒤에 공백(엔터, 스페이스 등)이 있는 경우,
         정의하지 않은 space(4px)가 자동 지정된다. 이것을 회피하는 방법이다. */
      font-size: 0;
      margin: 0;
      padding: 0;
    }

    .carousel-item {
      display: inline-block;
      list-style: none;
      padding: 5px;
    }

    .carousel-item:last-child {
      margin-right: 0;
    }

    .carousel-control {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      font-size: 2em;
      color: #fff;
      background-color: transparent;
      border-color: transparent;
      cursor: pointer;
      z-index: 99;
    }

    .carousel-control:focus {
      outline: none;
    }

    .carousel-control.prev {
      left: 0;
    }

    .carousel-control.next {
      right: 0;
    }
  </style>
</head>
<body>
  <div id="carousel" class="carousel-view">
    <button class="carousel-control prev">&laquo;</button>
    <ul class="carousel-container">
      <li class="carousel-item">
        <a href="#">
          <img src="http://via.placeholder.com/400x150/3498db/fff&text=1">
        </a>
      </li>
      <li class="carousel-item">
        <a href="#">
          <img src="http://via.placeholder.com/400x150/3498db/fff&text=2">
        </a>
      </li>
      <li class="carousel-item">
        <a href="#">
          <img src="http://via.placeholder.com/400x150/3498db/fff&text=3">
        </a>
      </li>
    </ul>
    <button class="carousel-control next">&raquo;</button>
  </div>
</body>
</html>
 

#10. text-overflow 프로퍼티

부모 영역을 벗어난 wrapping(자동줄바꿈)이 되지 않은 텍스트의 처리 방법을 정의한다. 이 프로퍼티를 사용하기 위해서는 아래의 조건이 필요하다.

  • width 프로퍼티가 지정되어 있어야 한다. 이를 위해 필요할 경우 block 레벨 요소로 변경하여야 한다.
  • 자동 줄바꿈을 방지하려면 white-space 프로퍼티를 nowrap으로 설정한다.
  • overflow 프로퍼티에 반드시 “visible” 이외의 값이 지정되어 있어야 한다.
/* 부모 영역을 벗어난 텍스트를 잘라내어 보이지 않게 하고 말줄임표(...)를 표시한다. */
.truncate {
  width: 150px;             /* width가 지정되어 있어야 한다. */
  white-space: nowrap;      /* 자동 줄바꿈을 방지 */
  overflow: hidden;         /* 반드시 "visible" 이외의 값이 지정되어 있어야 한다. */
  text-overflow: ellipsis;  /* ellipsis or clip */
}

text-overflow 프로퍼티에 설정할 수 있는 프로퍼티 값은 아래와 같다.


프로퍼티값 Description   
clip 영역을 벗어난 텍스트를 표시하지 않는다. (기본값)  
ellipsis 영역을 벗어난 텍스트를 잘라내어 보이지 않게 하고 말줄임표(…)를 표시한다.  
<!– <string> 프로퍼티 값으로 지정한 임의의 문자열을 출력한다. Firefox(9.0~)만 지원하는 기능이다. –>
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    div {
      width: 150px; /* width가 지정되어 있어야 한다. */
      height: 150px;
      padding: 10px;
      margin: 40px;
      border-radius: 6px;
      border-color: gray;
      border-style: dotted;
      white-space: nowrap; /* 자동 줄바꿈을 방지 */
      overflow: hidden;    /* 반드시 "visible" 이외의 값이 지정되어 있어야 한다. */
    }
    .clip     { text-overflow: clip; }
    .ellipsis { text-overflow: ellipsis; }
  </style>
</head>
<body>
  <h1>text-overflow</h1>
  <div class="clip">
    <h3>clip</h3>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit
  </div>
  <div class="ellipsis">
    <h3>ellipsis</h3>
    Lorem ipsum dolor sit amet, consectetur adipisicing elit
  </div>
</body>
</html>
 

#11. word-wrap 프로퍼티

한 단어의 길이가 길어서 부모 영역을 벗어난 텍스트의 처리 방법을 정의한다. link 등을 표기할 때(e.g. https://poiemaweb.com/css3-font-text) 그 길이가 매우 길어지는데 이 프로퍼티를 사용하지 않으면 부모 영역을 넘어가게 된다.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    div {
      width: 150px;
      height: 150px;
      padding: 10px;
      margin: 40px;
      border-radius: 6px;
      border-color: gray;
      border-style: dotted;
    }
    .word-wrap { word-wrap: break-word; }
  </style>
</head>
<body>
  <h1>word-wrap</h1>
  <div>
    Floccinaucinihilipilification https://poiemaweb.com/css3-font-text
  </div>
  <div class="word-wrap">
    Floccinaucinihilipilification https://poiemaweb.com/css3-font-text
  </div>
</body>
</html>
 

#12. word-break 프로퍼티

한 단어의 길이가 길어서 부모 영역을 벗어난 텍스트의 처리 방법을 정의한다.

word-wrap 프로퍼티는 단어를 어느 정도는 고려하여 개행하지만(.,- 등을 고려한다) word-break: break-all;는 단어를 고려하지 않고 부모 영역에 맞추어 강제 개행한다.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    div {
      width: 150px;
      height: 150px;
      padding: 10px;
      margin: 40px;
      border-radius: 6px;
      border-color: gray;
      border-style: dotted;
    }
    .word-wrap  { word-wrap: break-word; }
    .word-break { word-break: break-all; }
  </style>
</head>
<body>
  <div>
    Floccinaucinihilipilification https://poiemaweb.com/css3-font-text
  </div>

  <h1>word-wrap</h1>
  <div class="word-wrap">
    Floccinaucinihilipilification https://poiemaweb.com/css3-font-text
  </div>

  <h1>word-break</h1>
  <div class="word-break">
    Floccinaucinihilipilification https://poiemaweb.com/css3-font-text
  </div>
</body>
</html>
 

 

2.8 요소의 위치 정의

 

1. position 프로퍼티

position 프로퍼티는 요소의 위치를 정의한다. top, bottom, left, right 프로퍼티와 함께 사용하여 위치를 지정한다.

#1.1 static (기본위치)

static은 position 프로퍼티의 기본값으로 position 프로퍼티를 지정하지 않았을 때와 같다.

기본적인 요소의 배치 순서에 따라 위에서 아래로, 왼쪽에서 오른쪽으로 순서에 따라 배치되며 부모 요소 내에 자식 요소로서 존재할 때는 부모 요소의 위치를 기준으로 배치된다.

기본적으로 이 값을 지정할 일은 없지만 이미 설정된 position을 무력화하기 위해 사용될 수 있다.

좌표 프로퍼티(top, bottom, left, right)를 같이 사용할 수 없으며 사용할 경우에는 무시된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body { margin: 0; }
    .parent {
      width: 150px;
      height: 150px;
      background: #bcbcbc;
      border: 1px solid #bcbcbc;
    }
    .static-box {
      position: static;
      background: #2E303D;
      color: #e55c3c;
      font-weight: bold;
      text-align: center;
      line-height: 150px;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="static-box">static box</div>
  </div>
</body>
</html>
 

#1.2 relative (상대위치)

기본 위치(static으로 지정되었을 때의 위치)를 기준으로 좌표 프로퍼티(top, bottom, left, right)를 사용하여 위치를 이동시킨다. static을 선언한 요소와 relative를 선언한 요소의 차이점은 좌표 프로퍼티의 동작 여부뿐이며 그외는 동일하게 동작한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body { margin: 0; }
    .parent {
      width: 150px;
      height: 150px;
      background: #bcbcbc;
      border: 1px solid #bcbcbc;
      margin: 50px;
    }
    .relative-box {
      position: relative;
      top: 50px; left: 50px;
      background: #2E303D;
      color: #e55c3c;
      font-weight: bold;
      text-align: center;
      line-height: 150px;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="relative-box">relative box</div>
  </div>
</body>
</html>
 

위 예제를 보면 parent 클래스의 자식인 relative-box 클래스 요소의 width, height가 부모 요소와 동일하다. 이는 상속에 의한 것이 아니라(width, height는 상속되지 않는다.) relative를 적용한 요소는 좌표 프로퍼티가 적용되는 것만 다를 뿐 그 이외는 static을 지정했을 때와 동일하게 동작하기 때문이다. 즉, width는 100%가 적용되어 부모 요소의 width와 동일한 값을 갖게된 것이고, hight는 auto가 적용되지만 line-height: 150px이 적용되어 부모 요소와 hight가 동일하게 된 것이다.

#1.3 absolute (절대위치)

부모 요소 또는 가장 가까이 있는 조상 요소(static 제외)를 기준으로 좌표 프로퍼티(top, bottom, left, right)만큼 이동한다. 즉, relative, absolute, fixed 프로퍼티가 선언되어 있는 부모 또는 조상 요소를 기준으로 위치가 결정된다.

만일 부모 또는 조상 요소가 static인 경우, document body를 기준으로 하여 좌표 프로퍼티대로 위치하게 된다.

따라서 부모 요소를 배치의 기준으로 삼기 위해서는 부모 요소에 relative를 정의하여야 한다.

이때 다른 요소가 먼저 위치를 점유하고 있어도 뒤로 밀리지 않고 덮어쓰게 된다. (이런 특성을 부유 또는 부유 객체라 한다)

absolute 선언 시, block 레벨 요소의 width는 inline 요소와 같이 content에 맞게 변화되므로 적절한 width를 지정하여야 한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body { margin: 0; }
    .parent {
      width: 200px;
      height: 200px;
      background: #bcbcbc;
      border: 1px solid #bcbcbc;
      margin: 50px 0 0 300px;
      position: relative;
    }
    .absolute-box {
      position: absolute;
      height: 200px; width: 200px;
      top: 50px; left: 50px;
      color: #e55c3c;
      font-weight: bold;
      text-align: center;
      background: #2E303D;
      line-height: 200px;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="absolute-box">absolute box (in parent)</div>
  </div>
  <div class="absolute-box">absolute box (no parent)</div></body>
</html>
 

relative 프로퍼티와 absolute 프로퍼티의 차이점은 아래와 같다.

relative 프로퍼티는 기본 위치(static으로 지정되었을 때의 위치)를 기준으로 좌표 프로퍼티(top, bottom, left, right)을 사용하여 위치를 이동시킨다. 따라서 무조건 부모를 기준으로 위치하게 된다.

absolute 프로퍼티는 부모에 static 이외의 position 프로퍼티가 지정되어 있을 경우에만 부모를 기준으로 위치하게 된다. 만일 부모, 조상이 모두 static 프로퍼티인 경우, document body를 기준으로 위치하게 된다.

따라서 absolute 프로퍼티 요소는 부모 요소의 영역을 벗어나 자유롭게 어디든지 위치할 수 있다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body { margin: 0;}
    .parent {
      width: 150px;
      height: 150px;
      background: #bcbcbc;
      border: 1px solid #bcbcbc;
      margin: 50px;
      float: left;
      /*position: relative;*/
    }
    .relative-box {
      position: relative;
      top: 10px; left: 10px;
      width: 150px;
      height: 150px;
      background: #2E303D;
      color: #e55c3c;
      font-weight: bold;
      text-align: center;
      line-height: 150px;
    }
    .absolute-box {
      position: absolute;
      top: 10px; left: 10px;
      width: 150px;
      height: 150px;
      background: #2E303D;
      color: #e55c3c;
      font-weight: bold;
      text-align: center;
      line-height: 150px;
    }
  </style>
</head>
<body>
  <div class="parent">
    <div class="absolute-box">absolute box</div>
  </div>
  <div class="parent">
    <div class="relative-box">relative box</div>
  </div>
</body>
</html>

 

https://oneroomtable.tistory.com/entry/CSS-%ED%8F%AC%EC%A7%80%EC%85%98-%EC%86%8D%EC%84%B1-%EC%84%A4%EB%AA%85-absolute-fixed-relative-%EC%B0%A8%EC%9D%B4-%EC%84%A4%EB%AA%85

참고

 

\1.4 fixed (고정위치)

부모 요소와 관계없이 브라우저의 viewport를 기준으로 좌표프로퍼티(top, bottom, left, right)을 사용하여 위치를 이동시킨다.

스크롤이 되더라도 화면에서 사라지지 않고 항상 같은 곳에 위치한다.

fixed 프로퍼티 선언 시, block 요소의 width는 inline 요소와 같이 content에 맞게 변화되므로 적절한 width를 지정하여야 한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    body { margin: 0; }
    .fixed-box {
      position: fixed;
      color: #e55c3c;
      font-weight: bold;
      text-align: center;
      background: #2E303D;
    }
    .sidebar {
      width: 50px;
      height: 100%;
      top: 0;
      right: 0;
      padding-top: 100px;
    }
    .footer {
      width: 200px;
      width: 100%;
      height: 50px;
      bottom: 0;
      left: 0;
      line-height: 50px;
    }
  </style>
</head>
<body>
  <div class="fixed-box sidebar">fixed box (side-bar)</div>
  <div class="fixed-box footer">fixed box (footer)</div>
</body>
</html>
 

#2. z-index 프로퍼티

z-index 프로퍼티에 큰 숫자값을 지정할수록 화면 전면에 출력된다. positon 프로퍼티가 static 이외인 요소에만 적용된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .normal-box {
      width: 100px; height: 100px;
    }
    .absolute-box {
      width: 100px; height: 100px;
      position: absolute;
    }
    /* z-index는 positon 프로퍼티가 static 이외인 요소에만 적용된다. */
    .orange {
      background-color: orange;
      z-index: 1000;
    }
    .red {
      background-color: red;
      left: 50px; top: 50px;
      z-index: 100;
    }
    .green {
      background-color: green;
      left: 100px; top: 100px;
      z-index: 10;
    }
    .blue {
      background-color: blue;
      left: 150px; top: 150px;
      z-index: 1;
    }
  </style>
</head>
<body>
  <div class="normal-box orange"></div>
  <div class="absolute-box red"></div>
  <div class="absolute-box green"></div>
  <div class="absolute-box blue"></div>
</body>
</html>
 

#3. overflow 프로퍼티

overflow 프로퍼티는 자식 요소가 부모 요소의 영역를 벗어났을 때 처리 방법을 정의한다.

프로퍼티값Description

visible 영역을 벗어난 부분을 표시한다. (기본값)
hidden 영역을 벗어난 부분을 잘라내어 보이지 않게 한다.
scroll 영역을 벗어난 부분이 없어도 스크롤 표시한다.(현재 대부분 브라우저는 auto과 동일하게 작동한다)
auto 영역을 벗어난 부분이 있을때만 스크롤 표시한다.
<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      width: 150px;
      height: 150px;
      padding: 10px;
      margin: 30px;
      font-size: 1.2em;
      border-radius: 6px;
      border-color: gray;
      border-style: dotted;
      float: left;
    }
    .visible { overflow: visible; }
    .hidden  { overflow: hidden; }
    .scroll  { overflow: scroll; }
    .auto    { overflow: auto; }
  </style>
</head>
<body>
  <h1>overflow</h1>
  <div class="visible"><h3>visible</h3>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
  <div class="hidden"><h3>hidden</h3>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
  <div class="scroll"><h3>scroll</h3>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
  <div class="auto"><h3>auto</h3>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
</body>
</html>
 

특정 방향으로만 스크롤을 표시하고자 할 때는 overflow-x 또는 overflow-y 프로퍼티를 사용한다.

div { overflow-y: auto; }

 

2.9 요소 정렬

float 프로퍼티는 주로 레이아웃을 구성할 때 블록 레벨 요소를 가로 정렬하기 위해 사용되는 중요한 기법이다. flexbox 레이아웃를 사용한다면 더욱 간단하게 정렬을 구현할 수도 있지만 flexbox 레이아웃을 지원하지 않는 IE를 고려해야 한다면 float 프로퍼티를 사용해야 한다.

float 프로퍼티는 본래 아래 예제와 같이 이미지와 텍스트가 있을 때, 이미지 주위를 텍스트로 감싸기 위해 만들어진 것이다.

<!DOCTYPE html>
<html>
<head>
  <style>
    img {
      float: left;
      margin-right: 10px;
    }
  </style>
</head>
<body>
  <img src="https://poiemaweb.com/img/doug.jpg">
  <div>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
</body>
</html>
 

float 프로퍼티는 해당 요소를 다음 요소 위에 떠 있게(부유하게) 한다. 여기서 떠 있다(float)는 의미는 요소가 기본 레이아웃 흐름에서 벗어나 요소의 모서리가 페이지의 왼쪽이나 오른쪽에 이동하는 것이다. float 프로퍼티를 사용할 때 요소의 위치를 고정시키는 position 프로퍼티의 absolute를 사용하면 안된다.

프로퍼티값Description

none 요소를 떠 있게 하지 않는다. (기본값)
right 요소를 오른쪽으로 이동시킨다
left 요소를 왼쪽으로 이동시킨다.

#1. 정렬

float 프로퍼티를 사용하지 않은 블록 요소들은 수직으로 정렬된다. float:left; 프로퍼티를 사용하면 왼쪽부터 가로 정렬되고, float:right; 프로퍼티를 사용하면 오른쪽부터 가로 정렬된다.

오른쪽 가로 정렬의 경우, 먼저 기술된 요소가 가장 오른쪽에 출력되므로 출력 순서가 역순이 된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      color: white;
      font-weight: bold;
      font-size: 50px;
      border-radius: 6px;
      width: 100px;
      height: 100px;
      margin: 10px;
      padding: 10px;
    }
    .d1, .d2 {
      float: left;
    }
    .d1 {
      background: red;
    }
    .d2 {
      background: orange;
    }
    .d3, .d4 {
      float: right;
    }
    .d3 {
      background: red;
    }
    .d4 {
      background: orange;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="box d1"> 1 </div>
    <div class="box d2"> 2 </div>
    <div class="box d3"> 3 </div>
    <div class="box d4"> 4 </div>
  </div>
</body>
</html>
 

float 프로퍼티는 좌측, 우측 가로 정렬만 할 수 있다. 중앙 가로 정렬은 margin 프로퍼티를 사용해야 한다.

div {
  width: 960px;
  margin: 0 auto;
}

#2. width

width 프로퍼티의 기본값은 100%이므로 width 프로퍼티값을 지정하지 않은 block 요소는 부모 요소의 가로폭을 가득 채운다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      color: white;
      font-weight: bold;
      font-size: 30px;
      line-height: 50px;
      height: 50px;
      margin: 0 10px;
      padding: 10px;
    }
    .d1 {
      background: red;
    }
    .d2 {
      background: orange;
    }
  </style>
</head>
<body>
  <div class="box d1"> div </div>
  <div class="box d2"> div </div>
</body>
</html>
 

width 프로퍼티를 선언하지 않은 block 레벨 요소에 float 프로퍼티가 선언되면 width가 inline 요소와 같이 content에 맞게 최소화되고 다음 요소 위에 떠 있게(부유하게) 된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      color: white;
      font-weight: bold;
      font-size: 30px;
      line-height: 50px;
      height: 50px;
      margin: 0 10px;
      padding: 10px;
    }
    .d1 {
      float: left;
      background: red;
    }
    .d2 {
      background: orange;
    }
  </style>
</head>
<body>
  <div class="box d1"> float: left; </div>
  <div class="box d2"> div </div>
</body>
</html>
 

위 예제를 살펴보면 d1 클래스 요소에는 float: left;를 선언하였고 d2 클래스 요소에는 float를 선언하지 않았다. 이때 d1 클래스 요소는 width가 inline 요소와 같이 content에 맞게 최소화되고 다음 요소인 d2 클래스 요소 위에 떠 있게(부유하게) 된다.

주의할 것은 d1 클래스 요소가 d2 클래스 요소 위에 떠 있게 되어도 d2 클래스 요소의 width는 d1 클래스 요소가 차이한 width만큼 줄어들지 않고 100%를 유지한다는 것이다. 이는 d2 클래스 요소는 float를 선언하지 않았기 때문에 본래의 width를 유지하기 때문이다. 따라서 d2 클래스 요소는 본래의 width(100%)를 유지한 상태에서 d1 클래스 요소가 그 위에 위치한다.

#3. float 프로퍼티 관련 문제 해결 방법

#3.1 float 프로퍼티가 선언된 요소와 float 프로퍼티가 선언되지 않은 요소간 margin이 사라지는 문제

위 예제를 보면 두 요소는 차례대로 정렬된 것처럼 보이지만 사실은 float 프로퍼티가 선언된 요소가 다음 요소 위에 떠 있는(부유하고 있는) 상태이다. 따라서 두 요소간의 margin은 제대로 표현되지 않는다.

이것은 두번째 요소에 float 프로퍼티를 선언하지 않았기 때문에 발생하는 박스 모델 상의 문제이다. 이 문제를 해결하는 가장 쉬운 방법은 float 프로퍼티를 선언하지 않은 요소(.d2)에 overflow: hidden 프로퍼티를 선언하는 것이다.

overflow: hidden 프로퍼티는 자식 요소가 부모 요소의 영역보다 클 경우 넘치는 부분을 안보이게 해주는 역할을 하는데 여기서는 float 프로퍼티가 없어서 제대로 표현되지 못하는 요소를 제대로 출력해준다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .box {
      color: white;
      font-weight: bold;
      font-size: 30px;
      line-height: 50px;
      height: 50px;
      margin: 0 10px;
      padding: 10px;
    }
    .d1 {
      float: left;
      background: red;
    }
    .d2 {
      overflow: hidden;
      background: orange;
    }
  </style>
</head>
<body>
  <div class="box d1"> float: left; </div>
  <div class="box d2"> div </div>
</body>
</html>
 

두번째 요소에도 float 프로퍼티를 선언하면 overflow: hidden 프로퍼티는 선언하지 않아도 되지만 너비가 최소화된다.

#3.2 float 프로퍼티가 선언된 자식 요소를 포함하는 부모 요소의 높이가 정상적으로 반영되지 않는 문제

아래 예제를 보면 float 프로퍼티가 선언된 두개의 자식 요소를 포함하는 부모 요소의 높이가 정상적인 값을 가지지 못하는 문제가 발생한다. float 요소는 일반적인 흐름 상에 존재하지 않기 때문에 float 요소의 높이를 알 수 없기 때문인데 이 문제는 부모 요소 이후에 위치하는 요소의 정렬에 문제를 발생시킨다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      color: white;
      text-align: center;
      padding: 10px;
      background-color: #def0c2;
    }
    .d1, .d2 {
      float: left;
      width: 50%;
      padding: 20px 0;
    }
    .d1 {
      background-color: #59b1f6;
    }
    .d2 {
      background-color: #ffb5b4;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="d1">1</div>
    <div class="d2">2</div>
  </div>
  <div style="background:red;padding:10px;color:white;">3</div>
</body>
</html>
 

이 문제를 해결하는 가장 쉬운 방법은 float 프로퍼티가 선언된 자식 요소의 부모 요소(.container)에 overflow: hidden 프로퍼티를 선언하는 것이다.

.container {
  ...
  overflow: hidden;
}

다른 방법으로 부모 요소(.container)에 float 프로퍼티를 선언하는 방법도 있다. 하지만 부모 요소의 너비는 float된 두개의 자식요소의 콘텐츠를 표현할 수 있는 만큼만으로 작게 줄어들게 된다. 권장할 수 있는 방법은 아니다.

container 영역이 끝나기 직전 빈 요소를 만들고 clear:both를 설정하는 방법도 가능하다. 하지만 의미 없는 빈 요소를 사용하여야 하기 때문에 이 방법 역시 권장할 수 있는 방법은 아니다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      color: white;
      text-align: center;
      padding: 10px;
      background-color: #def0c2;
      /*overflow: hidden;*/
    }
    .d1, .d2 {
      float: left;
      width: 50%;
      padding: 20px 0;
    }
    .d1 {
      background-color: #59b1f6;
    }
    .d2 {
      background-color: #ffb5b4;
    }
    .clear {
      height: 0;
      clear: both;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="d1">1</div>
    <div class="d2">2</div>
    <div class="clear"></div>
  </div>
  <div style="background:red; padding:10px; color:white;">3</div>
</body>
</html>
 

overflow: hidden;과 함께 많이 사용되는 방법은 ::after 가상 요소 선택자를 이용하는 것이다. 가상 요소 선택자는 CSS2 문법(:after)과 CSS3 문법(::after)이 있는데 IE8까지 지원하는 CSS2 문법을 사용하는 편이 좋다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      color: white;
      text-align: center;
      padding: 10px;
      background-color: #def0c2;
      /*overflow: hidden;*/
    }
    .clearfix:after {
      content: "";
      display: block;
      clear: both;
    }
    .d1, .d2 {
      float: left;
      width: 50%;
      padding: 20px 0;
    }
    .d1 {
      background-color: #59b1f6;
    }
    .d2 {
      background-color: #ffb5b4;
    }
  </style>
</head>
<body>
  <div class="container clearfix">
    <div class="d1">1</div>
    <div class="d2">2</div>
  </div>
  <div style="background:red;padding:10px;color:white;">3</div>
</body>
</html>
 

부모 요소에 위 예제와 같이 사전에 작성한 clearfix 클래스만 추가하거나, 해당 요소를 선택하여 클리어 문법을 선언하면 되기 때문에 가장 깔끔하고 간편하다. 이 방법을 사용하는 것을 추천한다.

 

.clearfix:after {
  content: "";
  display: block;
  clear: both;
}

/* or */

selector:after {
  content: "";
  display: block;
  clear: both;
}

또 다른 방법은 float 프로퍼티 대신 display: inline-block;을 선언하는 것이다. 주의해야야 점은 inline-block 프로퍼티 요소를 연속 사용하는 경우, 두 요소 사이에 정의하지 않은 공백(4px)가 자동 지정되는 것이다.

 

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      color: white;
      text-align: center;
      padding: 10px;
      background-color: #def0c2;
    }
    .d1, .d2 {
      display: inline-block;
      width: 50%;
      padding: 20px 0;
    }
    .d1 {
      background-color: #59b1f6;
    }
    .d2 {
      background-color: #ffb5b4;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="d1">1</div>
    <div class="d2">2</div>
  </div>
  <div style="background:red;padding:10px;color:white;">3</div>
</body>
</html>
 

위 예제를 보면 .d1, .d2 요소에 display: inline-block;을 선언하여 텍스트와 같이 배치되도록 하였지만 두 요소 사이에 정의하지 않은 공백(4px)이 자동 지정되어 부모 요소의 width를 초과하여 가로 정렬이 되지 않았다.

이 현상을 회피하기 위해 부모 요소에 font-size: 0;을 선언하여 두 요소 사이에 정의하지 않은 공백을 제거한다.

<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      color: white;
      text-align: center;
      padding: 10px;
      background-color: #def0c2;
      /* 폰트 사이즈를 0으로 지정하여 두 요소 사이에 정의하지 않은 공백을 제거 */
      font-size: 0;
    }
    .d1, .d2 {
      display: inline-block;
      width: 50%;
      padding: 20px 0;
      /* 폰트 사이즈를 재지정 */
      font-size: 1rem;
    }
    .d1 {
      background-color: #59b1f6;
    }
    .d2 {
      background-color: #ffb5b4;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="d1">1</div>
    <div class="d2">2</div>
  </div>
  <div style="background:red;padding:10px;color:white;">3</div>
</body>
</html>
 

좀 더 자세한 회피 방법은 Fighting the Space Between Inline Block Elements를 참조하기 바란다.

 

2.10  스타일의 상속과 적용 우선 순위

 

1. 상속(Inheritance)

 프로퍼티 중에는 상속이 되는 것과 되지 않는 것이 있다.

 

property Inherit
width/height no
margin no
padding no
border no
box-sizing no
display no
visibility yes
opacity yes
background no
font yes
color yes
line-height yes
text-align yes
vertical-align no
text-decoration no
white-space yes
position no
top/right/bottom/left no
z-index no
overflow no
float no
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    .text-red {
      color: red;
      border: 1px solid #bcbcbc;
      padding: 10px;
    }
  </style>
</head>
<body>
  <div class="text-red">
    <h1>Heading</h1>
    <p>Paragraph<strong>strong</strong></p>
    <button>Button</button>
  </div>
</body>
</html>
 

color는 상속되는 프로퍼티로서 자식 요소는 물론 자손 요소까지 적용된다. 하지만 button처럼 요소에 따라 상속 받지 않는 경우도 존재한다.

border, padding은 상속되지 않는 요소로 하위 요소에 적용되지 않는다. W3C가 제공하는 Full property table의 Inherited?가 yes인 프로퍼티만 상속된다.

상속되지 않는 프로퍼티

상속되지 않는 경우(상속받지 않는 요소 또는 상속되지 않는 프로퍼티), inherit 키워드를 사용하여 명시적으로 상속받게 할 수 있다.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <style>
    .text-red {
      color: red;
      border: 1px solid #bcbcbc;
      padding: 10px;
    }
    .text-red button {
      color: inherit;
    }
    .text-red p {
      border: inherit;
      padding: inherit;
    }
  </style>
</head>
<body>
  <div class="text-red">
    <h1>Heading</h1>
    <p>Paragraph<strong>strong</strong></p>
    <button>Button</button>
  </div>
</body>
</html>
 

#2. 캐스캐이딩(Cascading)

요소는 하나 이상의 CSS 선언에 영향을 받을 수 있다. 이때 충돌을 피하기 위해 CSS 적용 우선순위가 필요한데 이를 캐스캐이딩(Cascading Order)이라고 한다.

캐스캐이딩에는 다음과 같이 세가지 규칙이 있다.

 

중요도 CSS가 어디에 선언 되었는지에 따라서 우선순위가 달라진다.
명시도 대상을 명확하게 특정할수록 명시도가 높아지고 우선순위가 높아진다.
선언순서 선언된 순서에 따라 우선 순위가 적용된다. 즉, 나중에 선언된 스타일이 우선 적용된다.

 

#2.1 중요도

CSS가 어디에 선언 되었는지에 따라서 우선순위가 달라진다.

  1. head 요소 내의 style 요소
  2. head 요소 내의 style 요소 내의 @import 
  3. <link> 로 연결된 CSS 파일
  4. <link> 로 연결된 CSS 파일 내의 @import 
  5. 브라우저 디폴트 스타일시트
/* style.css */
body {
  background-color: red;
  color: white;
}
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="style.css">
  <style>
    body {
      background-color: beige;
      color: navy;
    }
  </style>
</head>
<body>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</body>
</html>

#2.2 명시도

대상을 명확하게 특정할수록 명시도가 높아지고 우선순위가 높아진다.

!important > 인라인 스타일 > 아이디 선택자 > 클래스/어트리뷰트/가상 선택자 > 태그 선택자 > 전체 선택자 > 상위 요소에 의해 상속된 속성
<!DOCTYPE html>
<html>
<head>
  <style>
    p        { color: red !important; }
    #thing   { color: blue; }

    div.food { color: chocolate; }
    .food    { color: green; }
    div      { color: orange; }
  </style>
</head>
<body>
  <p id="thing">Will be Red.</p>
  <div class="food">Will be Chocolate.</div>
</body>
</html>
 

#2.3 선언순서

선언된 순서에 따라 우선 순위가 적용된다. 즉, 나중에 선언된 스타일이 우선 적용된다.

<!DOCTYPE html>
<html>
<head>
  <style>
    p { color: blue; }
    p { color: red; }

    .red { color: red; }
    .blue { color: blue; }
  </style>
</head>
<body>
  <p>Will be RED.</p>
  <p class="blue red">Will be BLUE.</p>
</body>
</html>