css 이미지 비율 유지 및 조정
1.padding 을 사용한 비율 조정
padding-top, 또는 padding-bottom을 이용하는 방법 padding 의 기준을 부모의 width로 가지기 위해서 부모 컨테이너 가 필요
- 부모 컨테이너에 padding-top, 또는 padding-bottom에 원하는 비율을 넣는다.
- (가로/세로)*100 calc()를 활용할수도 있다.
- position: relative; 를 이용해 기준을 잡고 padding-top(비율)에 벗어나는 부분은 overflow: hidden;를 이용해 안보이게한다.
- 자식요소(이미지)에 position: absolute; 적용하여 부모요소로부터 기준을 잡고 원하는 비율에 맞춰 잘라낼 수 있다.
/* 방법 1 (가로/세로)x100 */ .img_box { width: 100%; padding-top: 62.68%; background-color: red; overflow: hidden; position: relative; } .card_img { width: 100%; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
2. aspect-ratio
- css최신 기능으로 엘리먼트 비율을 한번에 설정할 수 있다.
- aspect-ratio : 3 / 2 한줄이면 3:2 비율이 만들어진다.
- div ,img 등 모든 엘리먼트에 적용 가능하다.
- 위의 방법처럼 부모요소를 만들어 비율에 맞춘 이미지 잘라내기도 가능하다.
- 이때 부모요소에 aspect-ratio 비율을 정해준다.
/* 방법 2 aspect-ratio */ .card_img { width: 300px ; aspect-ratio: 3 / 2; object-fit: cover; background-color: red; } // aspect-ratio 를 이용한 이미지 잘라내기 .parent { width: 200px; aspect-ratio: 21 / 9; } .img { display: block; /*img default display - inline-block*/ width: 100%; height: 100%; object-fit: cover; }