목 차
이미지 중앙 정렬하는 2가지 방법
이 글에서는 position 속성 중 absolute와 transform 속성 중 translate를 이용하여 이미지 중앙 정렬하는 방법과 display 속성 중 flex를 이용하여 이미지 중앙 정렬하는 방법에 대해 알아보겠습니다.
position - transform 이용하기
position 속성과 transform 속성을 이용하여 이미지 중앙 정렬할 수 있습니다.
<style>
.wrap{
position: absolute;
top: 50%;
left:50%;
transform: translate(-50%, -50%);
}
img{
width:200px;
}
</style>
<div class="wrap">
<img src="https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png" alt="image">
</div>
transform 속성을 제외하고 나머지를 적고 결과를 보면 아래 사진과 깉은 모양이 나옵니다. 확인해보세요.
position 속성 중 absolute는 해당 요소의 가장 가까운 요소에 대한 상대적으로 배치합니다. 또는 position 중에 relative를 적용한 요소가 있으면 그 기준으로 배치됩니다. 이 코드에서는 body가 기준이 됩니다.
position 설정 후 top과 left를 50% 주게 되면 body 요소를 기준으로 50%씩 떨어지게 됩니다.
transform으로 다양한 속성을 변경시킬 수 있습니다. translate(x,y)는 x축과 y축으로 해당 값만큼 위치를 바꾸는 속성값 입니다. 따라서 이미지 중앙 정렬하기 위해서는 이 속성값을 적용해야 합니다.
flex 이용하기
flex를 이용하여 이미지 중앙 정렬할 수 있습니다.
<style>
.wrap{
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
img{
width:200px;
}
</style>
<div class="wrap">
<img src="https://media.sproutsocial.com/uploads/2017/02/10x-featured-social-media-image-size.png" alt="image">
</div>
flex는 각 요소를 정렬할 수 있는 효율적인 속성값입니다. flex는 container와 items라는 개념이 있습니다. container는 items를 감싸는 부모 요소이며, 각 item을 정렬하기 위해서는 container가 필수입니다.
위 코드를 설명하자면 wrap은 부모 요소가 되며 img는 items가 됩니다.
container는 display, flex-direction, justify-content, align-items가 올 수 있습니다. justify-container와 align-items는 각각 주축과 교차축으로 나눌 수 있는데 x축, y축이라고 생각하면 됩니다. 물론, flex-direction이 column인 경우 서로 바뀝니다.
하지만, height 값을 주지 않았기 때문에 주축만 이동됩니다. 이때 100vh를 주어서 브라우저 화면을 꽉 채우면 중앙 정렬이 됩니다.