position absolute 가운데 정렬

지나가는 행인·2023년 11월 9일

아이스크림을 빨간색 선 안에 위치 시키려면?

회색 테두리 box_container
빨간색 선 box
아이스크림 ice_img

<!-- html -->
<div class="box_container">
   <div>
      <div class="box"></div>
      <img src="./assets/ice.jpg" alt="" class="ice_img" width="390" height="500">
   </div>
</div>
/* css */
.box_container {
   border: 5px solid #aaa;
   position: relative;
}
.box {
   width: 400px;
   height: 510px;
   border-left: 5px solid red;
   border-right: 5px solid red;
   margin: auto;
}
.ice_img {
   position: absolute;
   top: 0;
   left: 0;
   border: 5px solid blue;
}

기존 방법

left: 50%; 주면 사진 크기만큼 계산해서 margin-left: -계산값px; 해준다.

.ice_img {
   position: absolute;
   top: 0;
   left: 50%;
   margin-left: -200px;
   border: 5px solid blue;

하지만, 매번 값을 계산하기는 어렵다.

그래서 transform: translateX(-50%)을 사용

쉬운 방법

transform: translateX(-50%)을 사용
그냥 left: 50%는 요소 크기를 고려하지 않지만 transfomr: translateX()는 요소 크기를 고려하기 때문에 가능

.ice_img {
   position: absolute;
   top: 0;
   left: 50%;
   transform: translateX(-50%);
   border: 5px solid blue;

기존 방법과 동일하게 결과가 나온다.

하지만, IE는 9부터 지원한다.
https://caniuse.com/?search=transform

0개의 댓글