etc./StackOverFlow

CSS로 div의 종횡비 유지

청렴결백한 만능 재주꾼 2023. 5. 2. 22:10
반응형

질문자 :jackb


창의 너비가 변경됨에 따라 너비/높이를 변경할 수 div 를 만들고 싶습니다.

가로 세로 비율을 유지하면서 너비에 따라 높이를 변경할 수 있는 CSS3 규칙이 있습니까?

JavaScript를 통해 이 작업을 수행할 수 있다는 것을 알고 있지만 CSS만 사용하는 것이 좋습니다.

div 창 너비에 따른 종횡비 유지



padding-bottom 대한 백분율 값 <div> 를 생성하기만 하면 됩니다.

 .demoWrapper { padding: 10px; background: white; box-sizing: border-box; resize: horizontal; border: 1px dashed; overflow: auto; max-width: 100%; height: calc(100vh - 16px); } div { width: 100%; padding-bottom: 75%; background: gold; /** <-- For the demo **/ }
 <div class="demoWrapper"> <div></div> </div>

컨테이너 너비의 75%(가로 세로 비율 4:3)와 동일한 높이 <div> 가 생성됩니다.

이것은 패딩의 경우 다음과 같은 사실에 의존합니다.

백분율은 생성된 상자의 포함 블록 [...] 너비 에 대해 계산됩니다 (출처: w3.org , 강조 광산)

다른 종횡비 및 100% 너비에 대한 패딩 하단 값:

 aspect ratio | padding-bottom value --------------|---------------------- 16:9 | 56.25% 4:3 | 75% 3:2 | 66.66% 8:5 | 62.5%

div에 콘텐츠 배치:

div의 종횡비를 유지하고 콘텐츠가 늘어나지 않도록 하려면 절대 위치에 있는 자식을 추가하고 다음을 사용하여 래퍼 가장자리까지 늘려야 합니다.

 div.stretchy-wrapper { position: relative; } div.stretchy-wrapper > div { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }

여기 데모 와 더 자세한 데모가 있습니다.


Web_Designer

vw 단위:

요소 의 너비와 높이 모두에 vw 단위를 사용할 수 있습니다. 이렇게 하면 뷰포트 너비에 따라 요소의 종횡비가 유지됩니다.

vw : 뷰포트 너비의 1/100입니다. [ 엠디엔 ]

또는 뷰포트 높이에 vh 를 사용하거나 뷰포트 치수 중 더 작거나 크게 사용하기 위해 vmin / vmax 를 사용할 수도 있습니다(여기에서 논의).

예: 1:1 종횡비

 div { width: 20vw; height: 20vw; background: gold; }
 <div></div>

다른 종횡비의 경우 다음 표를 사용하여 요소의 너비에 따른 높이 값을 계산할 수 있습니다.

 aspect ratio | multiply width by ----------------------------------- 1:1 | 1 1:3 | 3 4:3 | 0.75 16:9 | 0.5625

예: 정사각형 div의 4x4 그리드

 body { display: flex; flex-wrap: wrap; justify-content: space-between; } div { width: 23vw; height: 23vw; margin: 0.5vw auto; background: gold; }
 <div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div>

여기 이 데모 가 포함된 Fiddle이 있으며 여기에 수직 및 수평 중심 콘텐츠가 있는 반응형 사각형 격자를 만드는 솔루션이 있습니다.


vh/vw 단위에 대한 브라우저 지원은 IE9+ 입니다. 자세한 내용은 canIuse를 참조하세요.


web-tiki

<svg>display:grid 사용하여 이 문제에 대한 현명한 솔루션 이라고 생각하는 것을 우연히 발견했습니다.

display:grid grid-area 사용하여 두 개(또는 그 이상)의 자식으로 동일한 공간을 차지할 수 있습니다.
이것은 그것들이 모두 플로우 콘텐츠이고, 겹침을 의미하며 , 더 큰 상자가 비율을 설정 한다는 것을 의미합니다.

그 중 하나는 비율 설정을 담당 <svg> 다른 하나는 실제 내용입니다. 실제 콘텐츠가 짧고 전체 비율을 채우지 않는 경우(그리고 이 비율로 공간의 중앙에 배치하려는 경우) 중앙에 배치하면 됩니다(아래의 첫 번째 실행 가능한 스니펫 참조).

 <div class="ratio"> <svg viewBox="0 0 1 1"></svg> <div> I'm square </div> </div>
 .ratio { display: grid; } .ratio > * { grid-area: 1/1; }

<svg> 의 계정을 원하는 대로 설정합니다.

  • <svg viewBox="0 0 4 3"></svg>
  • <svg viewBox="0 0 16 9"></svg>

 .ratio { display: grid; } .ratio > * { grid-area: 1/1; } /* below code NOT needed for setting the ratio * I just wanted to mark it visually * and center contents */ .ratio div { border: 1px solid red; display: flex; align-items: center; justify-content: center; }
 <div class="ratio"> <svg viewBox="0 0 7 1"></svg> <div> Fixed ratio 7:1 </div> </div>


콘텐츠 요소에 원하는 비율로 스크롤 가능한 영역에 더 많은 콘텐츠를 포함하는 솔루션이 필요한 경우 부모에 position:relative position:absolute; height:100%; overflow-y: auto; 흐름 콘텐츠 요소( <svg> )가 크기, 따라서 비율을 설정할 수 있도록 합니다.

 .ratio { display: grid; position: relative; } .ratio > * { grid-area: 1/1; } .ratio > div { height: 100%; overflow-y: auto; position: absolute; /* the rest is not needed */ border: 1px solid red; padding: 0 1rem; }
 <div class="ratio"> <svg viewBox="0 0 7 2"></svg> <div> <h1>Fixed ratio 7:2</h1> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. A scelerisque purus semper eget. Sem nulla pharetra diam sit amet nisl suscipit adipiscing bibendum. A cras semper auctor neque vitae tempus quam pellentesque nec. Morbi enim nunc faucibus a pellentesque sit amet porttitor. Arcu odio ut sem nulla. Sed viverra ipsum nunc aliquet bibendum enim facilisis gravida neque. Cras tincidunt lobortis feugiat vivamus at augue eget. Laoreet sit amet cursus sit amet. Amet nulla facilisi morbi tempus iaculis urna id volutpat. Leo in vitae turpis massa sed elementum tempus egestas sed. Egestas integer eget aliquet nibh. Dolor sit amet consectetur adipiscing elit. <p>Ut aliquam purus sit amet. Eget magna fermentum iaculis eu non diam phasellus vestibulum. Diam in arcu cursus euismod quis viverra nibh. Nullam vehicula ipsum a arcu cursus vitae congue. Vel orci porta non pulvinar neque laoreet suspendisse. At tellus at urna condimentum mattis pellentesque. Tristique senectus et netus et malesuada. Vel pretium lectus quam id leo in. Interdum velit euismod in pellentesque. Velit euismod in pellentesque massa placerat duis. Vitae suscipit tellus mauris a diam maecenas sed enim. <p>Mauris a diam maecenas sed enim ut sem. In hendrerit gravida rutrum quisque. Amet dictum sit amet justo donec enim diam. Diam vulputate ut pharetra sit amet aliquam id. Urna porttitor rhoncus dolor purus non enim praesent. Purus in massa tempor nec feugiat nisl pretium. Sagittis vitae et leo duis ut. Facilisi nullam vehicula ipsum a arcu cursus vitae congue mauris. Volutpat odio facilisis mauris sit amet massa vitae tortor condimentum. Aliquam purus sit amet luctus venenatis lectus magna. Sit amet purus gravida quis blandit turpis. Enim eu turpis egestas pretium aenean. Consequat mauris nunc congue nisi. Nunc sed id semper risus in hendrerit gravida rutrum. Ante metus dictum at tempor. Blandit massa enim nec dui nunc mattis enim ut. </div> </div>


@emjay가 아래 주석에서 언급했듯이 비율 svg는 적절하게 인코딩되어 있는 한 부모의 의사 요소 중 하나에 배치할 수 있습니다.

 .three-squares { display: grid; border: 1px solid red; } .three-squares > *, .three-squares:before { grid-area: 1/1; } .three-squares:before { content: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 3 1'%3E%3C/svg%3E"); line-height: 0; }
 <div class="three-squares"> <div>I'm 3:1</div> </div>

유사 요소 내부에서 사용되는 경우 <svg> 는 기본적으로 가변 높이(Chrome의 경우 4px , Firefox의 3.5px )의 기준선에 있는 대체된 요소 가 됩니다. line-height 에 따라 달라지므로 정확한 비율을 얻으려면 의사에서 line-height: 0 을 설정해야 합니다. 자세한 내용은 여기를 참조하십시오.


.ratio <svg> 가 마크업에 배치된 버전을 선호합니다(필요할 수 있는 각 개별 비율에 대한 클래스를 갖는 것과 반대).


tao

CSS로 하는 방법을 찾았지만, 자신의 웹사이트의 흐름에 따라 달라질 수 있으니 주의가 필요합니다. 내 웹 사이트의 유동적인 너비 부분에 일정한 종횡비로 비디오를 포함하기 위해 이 작업을 수행했습니다.

다음과 같이 삽입된 비디오가 있다고 가정해 보겠습니다.

 <object> <param ... /><param ... />... <embed src="..." ...</embed> </object>

그런 다음 "비디오" 클래스가 있는 div 안에 이 모든 것을 배치할 수 있습니다. 이 비디오 클래스는 아마도 웹사이트의 유동적인 요소가 될 것이므로 그 자체로는 직접적인 높이 제약이 없지만 브라우저의 크기를 조정하면 웹사이트의 흐름에 따라 너비가 변경됩니다. 이것은 비디오의 특정 종횡비를 유지하면서 포함된 비디오를 가져오려고 하는 요소일 것입니다.

이를 위해 "비디오" 클래스 div 내 포함된 개체 앞에 이미지를 넣습니다.

!!! 중요한 부분은 이미지에 유지하려는 올바른 종횡비가 있다는 것입니다. 또한 이미지의 크기가 레이아웃을 기반으로 얻을 것으로 예상되는 비디오(또는 AR을 유지하는 모든 것) 중 가장 작은 크기인지 확인하십시오. 이렇게 하면 이미지 크기가 백분율로 조정될 때 이미지 해상도의 잠재적인 문제를 피할 수 있습니다. 예를 들어 가로 세로 비율을 3:2로 유지하려면 3x2픽셀 이미지만 사용하지 마십시오. 어떤 상황에서는 작동할 수 있지만 테스트하지 않았으므로 피하는 것이 좋습니다.

웹 사이트의 유동 요소에 대해 이와 같은 최소 너비가 이미 정의되어 있어야 합니다. 그렇지 않은 경우 브라우저 창이 너무 작아질 때 요소가 잘리거나 겹치는 것을 방지하기 위해 그렇게 하는 것이 좋습니다. 어느 시점에서 스크롤 막대가 있는 것이 좋습니다. 웹 페이지의 가장 작은 너비는 약 600픽셀(고정 너비 열 포함) 정도입니다. 전화 친화적인 사이트를 다루지 않는 한 화면 해상도가 더 작아지지 않기 때문입니다. !!!

나는 완전히 투명한 png를 사용하지만 제대로 하면 결국 중요하지 않다고 생각합니다. 이와 같이:

 <div class="video"> <img class="maintainaspectratio" src="maintainaspectratio.png" /> <object> <param ... /><param ... />... <embed src="..." ...</embed> </object> </div>

이제 다음과 유사한 CSS를 추가할 수 있습니다.

 div.video { ...; position: relative; } div.video img.maintainaspectratio { width: 100%; } div.video object { position: absolute; top: 0px; left: 0px; width: 100%; height: 100%; } div.video embed {width: 100%; height: 100%; }

또한 일반적으로 복사/붙여넣기 포함 코드와 함께 제공되는 개체 및 포함 태그 내에서 명시적인 높이 또는 너비 선언을 제거해야 합니다.

작동 방식은 비디오 클래스 요소의 위치 속성과 원하는 항목이 특정 종횡비를 유지하는지에 따라 다릅니다. 요소에서 크기를 조정할 때 이미지가 적절한 종횡비를 유지하는 방식을 활용합니다. 그것은 너비/높이를 이미지에 의해 조정되는 비디오 클래스 요소의 100%로 강제하여 동적 이미지가 제공하는 공간을 최대한 활용하도록 비디오 클래스 요소에 있는 다른 모든 것을 알려줍니다.

꽤 멋지죠?

자신의 디자인과 함께 작동하도록 하려면 약간의 작업을 수행해야 할 수도 있지만 이것은 실제로 저에게 놀랍도록 잘 작동합니다. 일반적인 개념이 있습니다.


forgo

Elliot은 저에게 이 솔루션에 영감을 주었습니다. 감사합니다.

aspectratio.png 는 원하는 종횡비(제 경우에는 30x10픽셀) 크기의 완전히 투명한 PNG 파일입니다.

HTML

 <div class="eyecatcher"> <img src="/img/aspectratio.png"/> </div>

CSS3

 .eyecatcher img { width: 100%; background-repeat: no-repeat; background-size: 100% 100%; background-image: url(../img/autoresized-picture.jpg); }

참고: background-size 는 대상 브라우저에서 작동하지 않을 수 있는 css3 기능입니다. 상호 운용성을 확인할 수 있습니다( caniuse.com의 fe ).


Florian Neumann

2021 솔루션 - aspect-ratio CSS 속성 사용

 <div class='demo'></div>
 .demo { background: black; width: 500px; aspect-ratio: 4/3; }

다양한 브라우저에 대한 속성 지원


Tiago

Web_Designer의 답변에 추가하려면 <div> 의 높이(완전히 아래쪽 패딩 으로 구성됨)가 포함하는 요소 너비의 75%입니다. 다음은 좋은 요약입니다. http://mattsnider.com/css-using-percent-for-margin-and-padding/ . 왜 이렇게 해야 하는지 잘 모르겠지만, 그렇게 되어 있습니다.

div를 100%가 아닌 너비로 설정하려면 너비를 설정할 다른 래핑 div가 필요합니다.

 div.ar-outer{ width: 60%; /* container; whatever width you want */ margin: 0 auto; /* centered if you like */ } div.ar { width:100%; /* 100% of width of container */ padding-bottom: 75%; /* 75% of width of container */ position:relative; } div.ar-inner { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }

나는 최근에 Elliot의 이미지 트릭과 유사한 것을 사용하여 장치 해상도에 따라 다른 로고 파일을 제공하기 위해 CSS 미디어 쿼리를 사용할 수 있지만 <img> 가 자연스럽게 하는 것처럼 여전히 비례적으로 확장됩니다(로고를 배경 이미지로 설정 정확한 종횡비의 투명 .png). 그러나 Web_Designer의 솔루션은 http 요청을 저장합니다.


nabrown

여기 w3schools.com 에 언급되어 있고 이 허용된 답변 에서 다소 반복하여 백분율로 값을 패딩합니다(강조 광산).

포함하는 요소 의 너비에 대한 패딩을 백분율로 지정합니다.

따라서 16:9 종횡비를 유지하는 반응형 DIV의 올바른 예는 다음과 같습니다.

CSS

 .parent { position: relative; width: 100%; } .child { position: relative; padding-bottom: calc(100% * 9 / 16); } .child > div { position: absolute; top: 0; bottom: 0; left: 0; right: 0; }

HTML

 <div class="parent"> <div class="child"> <div>Aspect is kept when resizing</div> </div> </div>

JSFiddle에 대한 데모


Marc A

vh / vw 를 사용하는 방법을 보여 주므로 화면 중앙에 배치하는 방법도 필요합니다. 여기에 9:16 세로에 대한 스니펫 코드가 있습니다.

 .container { width: 100vw; height: calc(100vw * 16 / 9); transform: translateY(calc((100vw * 16 / 9 - 100vh) / -2)); }

translateY 는 이 중앙을 화면에 유지합니다. calc(100vw * 16 / 9) 는 9/16의 예상 높이입니다. (100vw * 16 / 9 - 100vh) 는 오버플로 높이이므로 overflow height/2 위로 올리면 화면 중앙에 유지됩니다.

풍경의 경우 16:9를 유지하고 사용을 보여줍니다.

 .container { width: 100vw; height: calc(100vw * 9 / 16); transform: translateY(calc((100vw * 9 / 16 - 100vh) / -2)); }

100:56.25 또는 100:75 를 미리 정의할 필요가 없습니다. 높이를 먼저 확인하려면 너비와 높이를 전환해야 합니다(예: height:100vh;width: calc(100vh * 9 / 16) 9:16 초상화의 경우.

다른 화면 크기에 맞게 조정하려는 경우에도 관심을 가질 수 있습니다.

  • 배경 크기 표지/포함
    • 위의 스타일은 너비:높이 비율에 따라 포함하는 것과 유사합니다.
  • 개체 맞춤
    • img/video 태그의 표지/포함
  • @media (orientation: portrait) / @media (orientation: landscape)
    • 비율을 변경하기 portrait / landscape 미디어 쿼리.

wener

이것은 허용되는 답변에 대한 개선 사항입니다.

  • 래퍼 div 대신 의사 요소를 사용합니다.
  • 가로 세로 비율은 부모 대신 상자의 너비를 기반으로 합니다.
  • 내용이 커지면 상자가 세로로 늘어납니다.

 .box { margin-top: 1em; margin-bottom: 1em; background-color: #CCC; } .fixed-ar::before { content: ""; float: left; width: 1px; margin-left: -1px; } .fixed-ar::after { content: ""; display: table; clear: both; } .fixed-ar-16-9::before { padding-top: 56.25%; } .fixed-ar-3-2::before { padding-top: 66.66%; } .fixed-ar-4-3::before { padding-top: 75%; } .fixed-ar-1-1::before { padding-top: 100%; } .width-50 { display: inline-block; width: 50%; } .width-20 { display: inline-block; width: 20%; }
 <div class="box fixed-ar fixed-ar-16-9">16:9 full width</div> <hr> <div class="box fixed-ar fixed-ar-16-9 width-50">16:9</div> <hr> <div class="box fixed-ar fixed-ar-16-9 width-20">16:9</div> <div class="box fixed-ar fixed-ar-3-2 width-20">3:2</div> <div class="box fixed-ar fixed-ar-4-3 width-20">4:3</div> <div class="box fixed-ar fixed-ar-1-1 width-20">1:1</div> <hr> <div class="box fixed-ar fixed-ar-16-9 width-20">16:9</div> <div class="box fixed-ar fixed-ar-16-9 width-50">16:9</div>


Salman A

svg를 사용할 수 있습니다. 컨테이너/래퍼 위치를 상대적으로 만들고 svg를 먼저 정적으로 배치한 다음 절대 위치 콘텐츠를 배치합니다(상단: 0; 왼쪽:0; 오른쪽:0; 하단:0;).

16:9 비율의 예:

image.svg: (src에서 인라인 가능)

 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 9" width="16" height="9"/>

CSS:

 .container { position: relative; } .content { position: absolute; top:0; left:0; right:0; bottom:0; }

HTML:

 <div class="container"> <img style="width: 100%" src="image.svg" /> <div class="content"></div> </div>

인라인 svg는 작동하지 않는 것 같지만 다음과 같이 svg를 urlencode하고 img src 속성에 포함할 수 있습니다.

 <img src="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%2016%209%22%20width%3D%2216%22%20height%3D%229%22%2F%3E" style="width: 100%;" />

Maciej Krawczyk

귀하의 솔루션을 기반으로 몇 가지 트릭을 만들었습니다.

당신이 그것을 사용할 때, 당신의 HTML은

 <div data-keep-ratio="75%"> <div>Main content</div> </div>

이런 식으로 사용하려면 다음을 작성하십시오. CSS:

 *[data-keep-ratio] { display: block; width: 100%; position: relative; } *[data-keep-ratio] > * { position: absolute; left: 0; right: 0; top: 0; bottom: 0; }

및 js(제이쿼리)

 $('*[data-keep-ratio]').each(function(){ var ratio = $(this).data('keep-ratio'); $(this).css('padding-bottom', ratio); });

그리고 이것을 사용하면 attr data-keep-ratio 를 높이/너비로 설정하면 됩니다.


Adam Pietrasiak

실제로 투표율이 높은 답변은 매우 좋은 솔루션이지만 이름이 aspect-ratio 새로운 CSS 기능이 있습니다.

다음과 같이 사용할 수 있습니다.

 .someClass { width: 100%; aspect-ratio: 4/3; }

높이가 자동으로 결정되지만 호환성 표를 참조하십시오.

여기에 이미지 설명 입력

프로젝트에 브라우저 지원이 중요한 경우 사용하지 마십시오. padding-bottom 기술을 사용합니다.


AmerllicA

대부분의 답변은 매우 훌륭하지만 대부분은 이미지의 크기가 이미 올바르게 지정되어 있어야 합니다... 다른 솔루션은 너비에만 작동하고 사용 가능한 높이에는 신경 쓰지 않지만 때로는 콘텐츠를 특정 높이에 맞추고 싶을 때도 있습니다. .

완전히 이식 가능하고 크기 조정 가능한 솔루션을 제공하기 위해 함께 결합하려고 시도했습니다... 트릭은 이미지의 자동 크기 조정에 사용하지만 사전 렌더링된 이미지 또는 모든 형태의 형식 대신 인라인 svg 요소를 사용하는 것입니다 두 번째 HTTP 요청...

 div.holder{ background-color:red; display:inline-block; height:100px; width:400px; } svg, img{ background-color:blue; display:block; height:auto; width:auto; max-width:100%; max-height:100%; } .content_sizer{ position:relative; display:inline-block; height:100%; } .content{ position:absolute; top:0; bottom:0; left:0; right:0; background-color:rgba(155,255,0,0.5); }
 <div class="holder"> <div class="content_sizer"> <svg width=10000 height=5000 /> <div class="content"> </div> </div> </div>

SVG의 너비 및 높이 속성에 큰 값을 사용했음을 주목하세요. SVG는 축소될 수 있으므로 최대 예상 크기보다 커야 하기 때문입니다. 이 예에서는 div의 비율을 10:5로 만듭니다.


Salketer

내가 하는 방법은 다음과 같습니다.

 [data-aspect-ratio] { display: block; max-width: 100%; position: relative; } [data-aspect-ratio]:before { content: ''; display: block; } [data-aspect-ratio] > * { display: block; height: 100%; left: 0; position: absolute; top: 0; width: 100%; } [data-aspect-ratio="3:1"]:before { padding-top: 33.33%; } [data-aspect-ratio="2:1"]:before { padding-top: 50%; } [data-aspect-ratio="16:9"]:before { padding-top: 56.25%; } [data-aspect-ratio="3:2"]:before { padding-top: 66.66%; } [data-aspect-ratio="4:3"]:before { padding-top: 75%; } [data-aspect-ratio="1:1"]:before { padding-top: 100%; } [data-aspect-ratio="3:4"]:before { padding-top: 133.33%; } [data-aspect-ratio="2:3"]:before { padding-top: 150%; } [data-aspect-ratio="9:16"]:before { padding-top: 177.77%; } [data-aspect-ratio="1:2"]:before { padding-top: 200%; } [data-aspect-ratio="1:3"]:before { padding-top: 300%; }

예를 들어 :

 <div data-aspect-ratio="16:9"><iframe ...></iframe></div>

원천


gordie

세로 또는 가로 보기에서 뷰포트 내부에 정사각형을 맞추려면(최대한 크게 하되 바깥쪽에는 아무것도 붙지 않음) portrait / landscape 방향에서 vw / vh 사용 간에 전환합니다.

 @media (orientation:portrait ) { .square { width :100vw; height:100vw; } } @media (orientation:landscape) { .square { width :100vh; height:100vh; } }

MoonLite

SVG를 사용하여 이를 달성할 수 있습니다.

경우에 따라 다르지만 어떤 경우에는 정말 유용합니다. 예를 들어 background-image 를 설정하거나 비율 16:9position:absolute<iframe> 을 포함하는 데 사용할 수 있습니다.

3:2 비율의 경우 viewBox="0 0 3 2" 등으로 설정합니다.

예시:

 div{ background-color:red } svg{ width:100%; display:block; visibility:hidden } .demo-1{width:35%} .demo-2{width:20%}
 <div class="demo-1"> <svg viewBox="0 0 3 2"></svg> </div> <hr> <div class="demo-2"> <svg viewBox="0 0 3 2"></svg> </div>


Jakub Muda

2020 솔루션 - 의사 요소의 그리드 및 패딩 사용

이 사건을 해결하기 위한 좀 더 신선한 방법을 찾았습니다. 이 솔루션은 모든 padding-bottom 메서드의 후손이지만 어떠한 position: absolute 자식, display: grid; 및 유사 요소.

여기에 .ratio::before with good old padding-bottom: XX%grid-area: 1 / 1 / 1 / 1; , 의사 요소가 그리드에서 위치를 유지하도록 합니다. 여기에 width: 0; 이것에 의해 주요 요소가 오버플로되는 것을 방지하기 위해 ( z-index 사용하지만 이것은 더 짧습니다).

그리고 우리의 주요 요소인 .ratio > *:first-childgrid-area: 1 / 1 / 1 / 1; .ratio::before 와 같은 위치에 있습니다. , 따라서 둘 다 동일한 그리드 셀 위치를 공유합니다. 이제 div에 모든 콘텐츠를 넣을 수 있으며 의사 요소는 너비/높이 비율을 결정하는 요소입니다. grid-area 에 대한 추가 정보.

 .ratio { display: grid; grid-template-columns: 1fr; max-width: 200px; /* just for instance, can be 100% and depends on parent */ } .ratio::before { content: ''; width: 0; padding-bottom: calc(100% / (16/9)); /* here you can place any ratio */ grid-area: 1 / 1 / 1 / 1; } .ratio>*:first-child { grid-area: 1 / 1 / 1 / 1; /* the same as ::before */ background: rgba(0, 0, 0, 0.1); /* just for instance */ }
 <div class="ratio"> <div>16/9</div> </div>


style 속성을 사용하여 HTML에 비율을 배치할 수 있지만. display: inline-grid 에서도 작동합니다.

 .ratio { display: inline-grid; grid-template-columns: 1fr; width: 200px; /* just for instance, can be 100% and depends on parent */ margin-right: 10px; /* just for instance */ } .ratio::before { content: ''; width: 0; padding-bottom: calc(100% / (var(--r))); /* here you can place any ratio */ grid-area: 1 / 1 / 1 / 1; } .ratio>*:first-child { grid-area: 1 / 1 / 1 / 1; /* the same as ::before */ background: rgba(0, 0, 0, 0.1); /* just for instance */ }
 <div class="ratio" style="--r: 4/3;"> <div>4/3</div> </div> <div class="ratio" style="--r: 16/9;"> <div>16/9</div> </div>


focus.style

특정 종횡비를 채우는 img 태그가 있는 솔루션을 공유하고 싶습니다. background 사용할 수 없었고 <img style="background:url(...)" /> 과 같은 스타일 태그를 사용하는 것을 선호하지 않습니다. 또한 너비가 100%이므로 일부 솔루션과 같이 고정된 크기로 설정할 필요가 없습니다. 반응형으로 확장됩니다!

 .wrapper { width: 50%; } .image-container { position: relative; width: 100%; } .image-container::before { content: ""; display: block; } .image-container img { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; } .ratio-4-3::before { padding-top: 75%; } .ratio-3-1::before { padding-top: calc(100% / 3); } .ratio-2-1::before { padding-top: 50%; }
 <div class="wrapper"> <!-- Just to make things a bit smaller --> <p> Example of an 4:3 aspect ratio, filled by an image with an 1:1 ratio. </p> <div class="image-container ratio-4-3"> <!-- Lets go for a 4:3 aspect ratio --> <img src="https://placekitten.com/1000/1000/" alt="Kittens!" /> </div> <p> Just place other block elements around it; it will work just fine. </p> </div>


LaVomit

캔버스 요소를 사용하여 종횡비를 유지하는 간단한 방법입니다.

아래 div의 크기를 조정하여 작동하는지 확인하세요.

저에게는 이 접근 방식이 가장 효과적이었습니다. 그래서 다른 사람들과 공유하여 그들도 혜택을 받을 수 있습니다.

 .cont { border: 5px solid blue; position: relative; width: 300px; padding: 0; margin: 5px; resize: horizontal; overflow: hidden; } .ratio { width: 100%; margin: 0; display: block; } .content { background-color: rgba(255, 0, 0, 0.5); position: absolute; top: 0; left: 0; width: 100%; height: 100%; margin: 0; }
 <div class="cont"> <canvas class="ratio" width="16" height="9"></canvas> <div class="content">I am 16:9</div> </div>

동적 높이에서도 작동합니다!

 .cont { border: 5px solid blue; position: relative; height: 170px; padding: 0; margin: 5px; resize: vertical; overflow: hidden; display: inline-block; /* so the div doesn't automatically expand to max width */ } .ratio { height: 100%; margin: 0; display: block; } .content { background-color: rgba(255, 0, 0, 0.5); position: absolute; top: 0; left: 0; width: 100%; height: 100%; margin: 0; }
 <div class="cont"> <canvas class="ratio" width="16" height="9"></canvas> <div class="content">I am 16:9</div> </div>


kess

2개의 div가 있다고 가정해 보겠습니다. 외부 div는 컨테이너이고 내부는 비율(img 또는 youtube iframe 등)을 유지하는 데 필요한 모든 요소가 될 수 있습니다.

HTML은 다음과 같습니다.

 <div class='container'> <div class='element'> </div><!-- end of element --> <div><!-- end of container -->

"요소" 비율 => 4:1 또는 2:1의 비율을 유지해야 한다고 가정해 보겠습니다.

CSS는 이렇게 생겼습니다.

 .container{ position: relative; height: 0 padding-bottom : 75% /* for 4 to 3 ratio */ 25% /* for 4 to 1 ratio ..*/ } .element{ width : 100%; height: 100%; position: absolute; top : 0 ; bottom : 0 ; background : red; /* just for illustration */ }

패딩은 %로 지정된 경우 높이가 아닌 너비를 기준으로 계산됩니다. .. 기본적으로 너비는 중요하지 않으며 높이는 항상 이를 기반으로 계산됩니다. 비율을 유지합니다.


Ahmed Eid

글쎄요, 우리는 최근 CSS에서 aspect-ratio 속성을 사용할 수 있는 기능을 받았습니다.

https://twitter.com/Una/status/1260980901934137345/photo/1

참고 : 지원은 아직 최고가 아닙니다 ...

https://caniuse.com/#search=종횡비

편집: 이제 가로 세로 비율을 사용할 수 있습니다!

https://web.dev/aspect-ratio/


AdamKniec

아이디어나 해킹일 뿐입니다.

 div { background-color: blue; width: 10%; transition: background-color 0.5s, width 0.5s; font-size: 0; } div:hover { width: 20%; background-color: red; } img { width: 100%; height: auto; visibility: hidden; }
 <div> <!-- use an image with target aspect ratio. sample is a square --> <img src="http://i.imgur.com/9OPnZNk.png" /> </div>


orlland

나는 이 문제를 꽤 자주 겪었기 때문에 이에 대한 JS 솔루션을 만들었습니다. 이것은 기본적으로 지정한 비율로 요소의 너비에 따라 domElement의 높이를 조정합니다. 다음과 같이 사용할 수 있습니다.

<div ratio="4x3"></div>

요소의 높이를 설정하기 때문에 요소는 display:block 또는 display:inline-block 이어야 합니다.

https://github.com/JeffreyArts/html-ratio-component


user007

Width: 100px 및 Height: 50px(즉, 2:1)을 유지하고 싶다고 가정해 보겠습니다.

 .pb-2to1 { padding-bottom: calc(50 / 100 * 100%); // ie, 2:1 }

Syed

새로운 종횡비 태그는 굉장하겠지만 내 div의 위치를 엉망으로 만들었습니다. 래퍼 div를 채우는 기존 솔루션은 작동하지만 부모 또는 뷰포트의 너비에 따라 크기만 조정 하므로 높이가 제한 요소일 때 문제가 됩니다 .

min() 함수가 매우 유용하다는 것을 알았고 다음과 같이 전통적인 방법을 조정했습니다.

 body{ background-image: linear-gradient(to top right, #FFE6B5, #B3CEBF); padding: 0; margin: 0 auto; overflow-y: hidden; /* this is to avoid scrolling when the height of the viewport is less than what the aspect ratio requires */ } .wrapper { position: relative; width: 100vw; max-height: 100vh; } .sixteen-by-nine.aspect-ratio { padding-bottom: 56.25% /* 9:16 ratio */ } .content { position: absolute; top: 0; bottom: 0; left: 0; right: 0; background-color: green } .centered { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); height: 100%; width: min(177.8vh, 100%); /* this always keeps a 16:9 ratio within the viewport */ font-size: min(3vh,1.7vw); /* if you are also interested in scaling the font size */ background-color: blue }
 <body> <div class="wrapper"> <div class="sixteen-by-nine aspect-ratio"></div> <div class="content" > <div class="centered"> <!-- stuff goes here --> </div> </div> </div> </body>


Valentino

방금 전체 너비를 차지하도록 크기가 조정된 2:1 div를 만들었지만 상단 또는 하단이 초과되는 경우 너비를 줄였습니다. 그러나 이것은 부모의 크기가 아닌 창의 크기에서만 작동합니다.

 #scene { position: relative; top: 50vh; left: 50vw; width: 100vw; height: 50vw; max-height: 100vh; max-width: calc(100vh * 2); transform: translate(-50%, -50%); }

2:1 대신 4:3 에 사용할 올바른 %를 찾을 수 있다고 확신합니다.


Peter Morris

새로운 솔루션을 사용했습니다.

 .squares{ width: 30vw height: 30vw

기본 종횡비로

 .aspect-ratio width: 10vw height: 10vh

그러나 이것은 전체 뷰포트에 상대적입니다. 따라서 뷰포트 너비의 30%인 div가 필요한 경우 30vw를 대신 사용할 수 있으며 너비를 알고 있으므로 calc 및 vw 단위를 사용하여 높이에서 재사용합니다.


Eshwaren Manoharen

다음은 선택적 고정 여백이 있는 div에서 세로 또는 가로로 16:9 종횡비를 유지하기 위한 솔루션입니다.

너비/높이 및 최대 너비/최대 높이 속성을 vw 단위로 조합한 것입니다.

이 샘플에서는 50px 위쪽 및 아래쪽 여백이 마우스를 가져갈 때 추가됩니다.

 html { height: 100%; } body { margin: 0; height: 100%; } .container { display: flex; justify-content: center; align-items: center; height: 100%; } .fixedRatio { max-width: 100vw; max-height: calc(9 / 16 * 100vw); width: calc(16 / 9 * 100vh); height: 100vh; /* DEBUG */ display: flex; justify-content: center; align-items: center; background-color: blue; font-size: 2rem; font-family: 'Arial'; color: white; transition: width 0.5s ease-in-out, height 0.5s ease-in-out; } .fixedRatio:hover { width: calc(16 / 9 * (100vh - 100px)); height: calc(100vh - 100px); }
 <div class='container'> <div class='fixedRatio'> 16:9 </div> </div>

JSFiddle에 대한 데모


Kevin Struillou

Chrome 88의 새로운 기능과 곧 다른 브라우저에서도 적용될 새로운 CSS aspect-ratio 속성입니다.

aspect-ratio CSS 속성은 자동 크기 및 기타 레이아웃 기능을 계산하는 데 사용되는 상자의 기본 종횡비를 설정합니다.

CSS 트릭 기사

추가 정보

 div { background: rebeccapurple; height:100px; margin:1em auto; } .square { aspect-ratio: 1 / 1; }
 <div class="square"> </div>


Paulie_D

출처 : http:www.stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css

반응형