프론트엔드/HTML · CSS · Javascript

[CSS] 이미지 비율 유지하기 (.sustain_ratio_img)

경호! 2022. 3. 2. 20:24
//이미지 비율 유지하기 : S
//사용법:
// <div class="sustain_ratio_img" style="background-image:url(); --pc-width: 1920; --pc-height: 600;"></div>
.sustain_ratio_img {
  display: block;
  width: 100%;
  height: 0;
  padding-bottom: calc(100% * ( var(--pc-height) / var(--pc-width) ));
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  text-indent: -9999px;
  &.is_mobile {
    padding-bottom: calc(100% * ( var(--mobile-height) / var(--mobile-width) ));
  }
}
//이미지 비율 유지하기 : E

반응형으로 어느 가로폭에서든 처음 지정한 비율을 유지하고 싶을때 만들었습니다.

많이 활용해주세요~

 

기본 img 태그로도 만들 수 있지만

저는 백그라운드 이미지가 좋더라구요..