<div>를 가운데(가로, 세로)로 정렬하는 방법은 무엇인가요?
<div style="width: 400px">hello</div>
의견 (0)
더 많은 의견 보기
<div style="width: 400px">hello</div>
margin-left와 margin-right를 auto로 설정하면 가로로 가운데 정렬할 수 있어요.
<style>
.element {
display: block;
margin-left: auto;
margin-right: auto;
}
</style>
<div class="element" style="width: 400px">hello</div>
<style>
.parent { text-align: center; }
.child { display: inline-block; }
</style>
<div class="parent">
<div class="child" style="width: 400px">hello</div>
</div>
가운데로 정렬될 엘리먼트의 높이를 알고 있는 경우 top을 50%로 하고 margin-top을 (높이 * -0.5) 로 하면 세로로 가운데 정렬할 수 있어요.
position: absolute도 잊지 마세요.
<style>
.parent { position: relative; }
.child {
position: absolute;
top: 50%;
height: 100px;
margin-top: -50px; /* (높이 * -0.5) */
}
</style>
<div class="parent" style="height: 400px">
<div class="child">hello</div>
</div>
가운데로 정렬될 엘리먼트의 높이를 모르는 경우 top을 50%로 하고 transform: translateY()를 -50%로 해서 세로로 가운데 정렬할 수 있어요.
(margin: auto를 사용할 수 없을 때는 같은 원리로 left를 50%로 하고 transform: translateX()를 -50%로 하면 가로로 가운데 정렬할 수도 있어요.)
<style>
.element {
top: 50%;
transform: translateY(-50%);
}
</style>
<div class="element">hello</div>