positon 사용
<div class="wrapper">
<div class="item"></div>
</div>
.wrapper{
position: relative;
width: 300px;
height: 300px;
background-color: blue;
}
.item{
width: 100px;
height: 100px;
background-color: orange;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
마진을 auto
로 주기 위해서는 반드시 width
,height
값이 지정되어 있어야한다.
이 방법은 사이트가 확대될때 요소의 가운데 배치를 보장하지 않음
부모요소의 width가 100%일때만 가능
.wrapper {
position: relative;
height: 400px;
background-color: blue;
}
.item {
width: 500px;
height: 300px;
background: orange;
position: absolute;
top: 40px;
left: 50%;
font-size: 200px;
text-align: center;
margin-left: -250px;
}
부모요소의 너비가 100%인 경우 자식요소를 left로 50%이동한뒤 left에 네거티브 마진으로 너비의 절반을 준다.
네거티브 마진대신
transform: translateX(-50%);
도 가능하다