본문으로 바로가기

[CSS] Div 가운데 정렬하는 방법

category Helloworld!/CSS 2016. 2. 5. 15:37

css의 postion 을 써서 div 박스를 가운데하려고 하는데 은근 복잡하고 막상 뜻대로 잘 안돼서 할때마다 항상 버벅인다.
이번에도 그래서...ㅎㅎㅎ

방법을 찾으려고 검색하다가 명쾌하게 정리해놓은 사이트가있어서 메모한다.

다음은 wrap이라는 div안에 center_box 라는 div를 wrap이라는 div를 기준으로 가운데 정렬하려 하는 예시이다.


- html

<div class="wrap">
    <div class="center_box&quot;">
        test
    </div>
</div>

- css
.wrap { 
    width: 100%; 
    position: relative; 
    background: red 
}
.center_box { 
    width: 300px; 
    hegiht: 200px; 
    position: absolute; 
    background: blue; 
    top: 50%; 
    left: 50%; 
    margin-top: -100px; 
    margin-left: -150px; 
}


wrap을 positionrelative 로 해놓은 다음에 center_box는 positionabsolute로 해놓는다. 
이건 wrap의 위치와 크기에 따라 center_box의 위치가 상대적으로 변경되게 하기위함이다. 

그다음 center_box에 top, left 값을 각각 50%준다. 
그럼 center_box의 맨위왼쪽 꼭지점이 wrap의 높이 반, 너비 반인 곳에 가게된다. 

이때 margin-topmargin-left 값을 각각 center_box의 새로값의 반, 너비값의 반을 마이너스 축으로 이동해준다. 
즉, center_box의 높이가 200이니 margin-top은 -100만큼 
너비가 300이니 margin-left는 -150만큼 이동을 하면 center_box 는 가운데로 위치하게된다.