css 가운데 정렬
📌 일반적인 가운데 정렬 방법
1. 부모요소가 block이고 자식 요소가 inline 일 때
.부모{
text-align: center;
}
2. block 일 때
.요소{
margin: 0 auto;
width: 100px; /* width값 필요함 */
}
📌 position: absolute 로 지정 되어있을 때
📝 html
<div class="parent">
<div class="child">
</div>
</div>
📝 css
.parent{
width: 100%;
position: relative;
}
.child{
width: 100px;
position: absolute;
}
1. top: 50% left: 50%
.child{
width: 100px;
position: absolute;
top: 50%;
left: 50%;
}
여기까지 해주면 자식요소가 정 가운데에 위치하게 되는데 다음과 같이 요소의 맨 왼쪽, 맨 위쪽 좌표를 기준으로 가운데로 가게 되어버린다.
위를 완전히 가운데로 오게 하기위해서는 다음과 같이 translate를 사용하거나 margin-left 를 이용하면 해결할 수 있다.
2-1. translate 이용
.child{
width: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
📢 이렇게 간단하게 가운데로 오게 할 수 있지만 can i use 사이트에서 확인하여 크로스 브라우징을 염두하여 사용해야한다.
2-2. margin 이용
.child{
width: 100px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -50px; /* width의 50% */
margin-top: -50px; /* height의 50% */
}
✌ 결과