Element의 Center를 찾기

화면 레이아웃을 만들고 스타일 잡다보면 vertical, horizontal center 만드는게 여간 까다로운게 아닙니다.
한번 정리를 해봅니다.

horizontal center는 간단한 부분이 많지만 vertical center가 까다롭고 parent element의 영향이 많습니다.

Horizontal Center

Text를 horizontal center 하는 것

Text는 horizontal center는 간단합니다. text-align을 사용하면 되는데 text를 둘러싸고 있는 element가 block인지 inline 속성인지에 따라 text-align을 하는 부분이 달라집니다.
Text를 둘러 싸고 있는 tag가 inline 속성이라면?

<!DOCTYPE html>
<html>
  <body>
    <div class="inline-wrap">
      <!-- text가 span이라는 inline tag에 둘러 쌓여 있습니다.-->
      <span class="inline">text</span>
    </div>
  </body>
</html>

위와 같은 경우 inline 클래스에 text-align이 아닌 그 위의 부모에 text-align을 적용해줘야 합니다.

.inline-wrap {
  text-align: center;
}

이유는 inline인 경우 text의 width에 맞춰서 영역이 생기기 때문에 text를 center로 할 공간이 없습니다.
그래서 center를 하려는 element의 block인 부모에 center를 지정해줘야 합니다.

Element를 horizontal center를 하는 방법

Element를 horizontal center를 하려면 현재 center를 하려는 element의 display 속성에 따라 달랍니다.
현재 element가 block 이라면 width를 지정해줘야 합니다. 아니면 inline or inline-block 이어야 합니다.

<!DOCTYPE html>
<html>
  <body>
    <div class="block">
      Block element center
    </div>
    <div class="inline-wrap">
      <div class="inline">
        Inline element center
      </div>
    </div>
  </body>
</html>    
.block {
  width: 100px;
  margin: 0 auto;
}
.inline-wrap {
  text-align: center;
}
.inline {
  /*display: inline-block;*/
  display: inline;
}

Vertical center

Text, Element를 vertical center 하는 방법

저나 많은 분들이 젤 어려워 하는 부분이 이 vertical center 하는 부분일꺼라 생각됩니다.
다음과 같은 방법들이 있습니다.

  1. position absolute
  2. display flex

Position absolute

이 방식은 부모 element의 속성이 relative이면서 height가 있어야 합니다.

<!DOCTYPE html>
  <body>
    <div id="relative">
      <div id="center">Vertical text</div> 
    </div>
  </body>
</html>
html,
body {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}

#relative {
  position: relative;
  height: 100%;
}

#center {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  /*
    여기서 transform을 쓰지않고 top에 calc로 계산해서 넣을 수도 있습니다.
  */
}

position absolute를 하면 부모에서 자식의 크기를 알 수 없기에 height를 채워 줄 수 있는 스타일이나 다른 element가 필요로 합니다.

display flex

이 방식은 flex를 사용하는 방식입니다.

<!DOCTYPE html>
<html>
  <body>
    <div id="relative">
      <div id="center">Vertical text</div> 
    </div>
  </body>
</html>
html,
body {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}

#relative {
  display: flex;
  height: 100%;
  align-items: center;
  /*
  justify-content: center;
  위 스타일을 쓰면 horizontal center도 가능합니다.
  */
}

실무에서 작업할 때는 좀 더 복잡하겠지만 flex를 잘 사용하면 깔끔한 레이아웃을 볼 수 있습니다.

profile
Front end

0개의 댓글