[css] div를 상하좌우 중앙정렬
본문 바로가기

Frontend/Markup

[css] div를 상하좌우 중앙정렬

 

html에 기본박스를 생성하고

    <div style="width: 100px; height: 100px; background-color: red;">
        <p>중앙</p>
    </div>

이를 상하좌우 중앙정렬하는데 여러방법이 있다.

div안에 '중앙'글씨를 정가운데로옮긴것은 flex를 이용하였고 이포스팅에서는 div만 다룰예정이므로 생략.

 

해결1 - 모든브라우저상에 표현이가능하나 고정적인 w,h값필요

       body div{position:absolute; top:50%; left:50%;}

 

해결 2 - 쉽고빠르지만 익스플로어9이상에서만 - 모바일용

body div{position:relative; left:50%; top:50%; transform: translateY(-50%);}

 

해결3 - IE8이상 중첩구조필요(table>table-cell>inline-block)

이때는 html에서 div가 여러개야함

<div class="layer">
        <div class="layer_inner">
            <div class="content">
                <div style="width: 100px; height: 100px; background-color: red;">
                    blablabla
                </div>
                <div style="width: 100px; height: 100px; background-color: blue;">
                    blablabla
                </div>
                <div style="width: 100px; height: 100px; background-color: yellow;">
                    blablabla
                </div>
            </div>
        </div>
    </div>
        .layer{
            display: table;
            width: 100%;
            height: 100%;
        }
        .layer_inner{
            display: table-cell;
            text-align: center;
            vertical-align: middle;
        }
        .content{
            display: inline-block;
        }
        .content div{float:left;}

 

해결4 grid

display:grid
place-content:center

참고사이트

https://saimplay.tistory.com/115

 

[ CSS 응용 ] DIV 중앙정렬 방법 총정리

| 개요 사이트를 디자인 하다보면 여러가지 정렬방식들이 기초적인 text-align속성과 position속성으로 정렬을 할 수 있다고 설명을 해드린적이 있습니다. 그렇다면 이번엔 조금 더 들어가 Div객체를

saimplay.tistory.com

https://codepen.io/mrcow/pen/hGHsg

 

Vertical Align with translateY(-50%)

...

codepen.io

 

반응형