개인 프로젝트에서 iframe으로 비디오를 받아오는 작업이 있었다.
@midea 쿼리를 사용해 화면 크기마다 비디오의 넓이와 높이를 일일이 지정했는데 코드가 지저분하다는 생각이 들었다.
구글링을 해보니 aspect-ratio라는 속성이 있어서 정리해 보려 한다.
aspect-ratio란?
- 요소의 가로(width)와 세로(height) 비율을 지정할 수 있는 CSS 속성이다.
- 비율만 설정하면 너비에 따라 자동으로 높이를 계산해 준다.
- 반응형 레이아웃에 유용하다.
기본 문법
.box {
aspect-ratio: 가로 / 세로;
}
사용 예시
index.html
<div class="video-wrapper">
<iframe src=`https://www.youtube.com/embed/${videoId}`></iframe>
</div>
styles.css
.video-wrapper {
width: 100%;
aspect-ratio: 16 /9;
}
.video-wrapper iframe {
width: 100%;
height: 100%;
border: none;
}
주의할 점
- width나 height 중 하나 이상 설정해야 비율이 적용된다.
- 부모 요소의 크기에 따라 자동으로 조절되도록 하려면 width: 100% 또는 height: auto 등을 함께 사용하면 된다.
- img 태그에는 aspect-ratio보다 object-fit을 사용하는 것이 안전하다.
공식 문서 참고
aspect-ratio - CSS | MDN
The aspect-ratio CSS property allows you to define the desired width-to-height ratio of an element's box. This means that even if the parent container or viewport size changes, the browser will adjust the element's dimensions to maintain the specified widt
developer.mozilla.org