본문 바로가기

웹:WEB/유용한정보

DIV 레이어 가로 세로 가운데 정렬 하기

▒ DIV레이어 가로 세로 가운데 정렬 하기

 

가로 가운데 정렬은 text-align:center , margin:0 auto; 등

CSS가 작동이 잘되는 반면 세로 가운데 정렬은 그렇게 쉽지만은 않다.

그래서 코딩을 할 때마다 여기 저기 검색을 하면서 했었던 기억이...ㅎㅎ

 

아무튼 이 포스팅에서는 3가지 방법만을 소개 하지만 이 방법 말고도 여러 방법이 있다는 것을 기억하자! 

 

■ position:absolute

<style>
  .wrapper {
         width:100%;
         height:500px;
         position:relative;
         background-color:#57606f;
        }
  .wrapper > div{
         width:300px;
         height:300px;
         position:absolute;
         margin:auto;
         left:0;
         top:0;
         bottom:0;
         right:0;         
         background-color: #68b151;}
</style>


<div class="wrapper">
     <div>연두색박스</div>
</div>
가변적인(반응형) 요소에도 적용이 가능하나 크기가 없는 경우에는 적용이 안된다.

 

 

 결과 

 

 

■ display:table / display:table-cell / vertical-align:middle

| 인라인요소

<style>
  .box {
      display:table;
      width:300px;
      height:300px;      
      background-color:#68b151;
    }
    .box > div {
      display:table-cell;
      vertical-align:middle;
      text-align:center;
    }
</style>


<div class="box">
      <div>
        가운데정렬
      </div>
</div>

 

| 블럭요소

<style>
.box {
      display:table;
      width:300px;
      height:300px;
      background-color: #68b151;
    }
    .box > div {
      display:table-cell;
      vertical-align:middle;
    }
    .box > div > p {
      height: 100px;
      width: 100px;
      background: #dddddd;
      margin:0 auto;
      text-align:center;}
</style>


<div class="box">
      <div>
        <p>박스</p>
      </div>
</div>

 

 

 

 

■ line-height

<style>
.box2 {
      width:300px;
      height:300px; 
      background-color:#57606f;
    }
    .box2 > div {
      text-align:center;
      line-height:300px;
      color:#ffffff;
    }
</style>


<div class="box2">
      <div>가운데정렬</div>
 </div>
감싸는 요소의 height와 line-height 값이 같으면 된다.
그러나 텍스트가 한 줄이상 넘어가면 line-height값 때문에 쓰기 불편하다.