sourcecode

CSS를 사용하여 div의 애스펙트비를 유지합니다.

codebag 2023. 4. 8. 08:26
반응형

CSS를 사용하여 div의 애스펙트비를 유지합니다.

이 좋은 작품을 요.div창 너비의 변화에 따라 너비/높이를 변경할 수 있습니다.

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

JavaScript로 할 수 있다는 것은 알지만, CSS만 사용하는 것이 좋습니다.

창폭에 따른 가로 세로 비율을 유지하다

만 .<div>「」에 .padding-bottom 이렇게요.

.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>

그그가 .<div>'75%' '4:3'입니다.

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

백분율은 생성된 상자의 포함 블록 너비에 따라 계산됩니다. [...] (출처: 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를 늘리지 않도록 하려면 절대 위치에 있는 아이를 추가하고 다음과 같이 랩의 가장자리까지 늘려야 합니다.

div.stretchy-wrapper {
  position: relative;
}

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

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

div와 같은 요소에 고정 애스펙트비를 지정하는 방법은 여러 가지가 있습니다.그 중 두 가지는 다음과 같습니다.

. 1. »aspect-ratioCSS 성 c

div {
  aspect-ratio: 1 / 1;
  width: 50%;
  background: teal;
}
<div>aspect-ratio: 1 / 1;</div>

이것이 가장 심플하고 유연한 솔루션입니다.요소의 고정 폭 대 높이(또는 높이 대 폭) 가로 세로 비율을 직접 지정합니다., 요소 높이에 따라 가로 세로 비율을 지정할 수도 있습니다.
크기.vw유닛 테크닉) 요소의 폭 또는 높이에 의존합니다.MDN에 대한 자세한 정보는 다른 회피책과 비교하여 매우 강력합니다.

이것은 현대적인 자산(2021년)입니다.최신 브라우저는 모두 지원합니다.정확한 브라우저 지원에 대해서는 caniuse를 참조하십시오.

다음으로 애스펙트비가 다른 예를 몇 가지 나타냅니다.

.ar-1-1  {aspect-ratio: 1 / 1;}
.ar-3-2  {aspect-ratio: 3 / 2;}
.ar-4-3  {aspect-ratio: 4 / 3;}
.ar-16-9 {aspect-ratio: 16 / 9;}
.ar-2-3  {aspect-ratio: 2 / 3;}
.ar-3-4  {aspect-ratio: 3 / 4;}
.ar-9-16 {aspect-ratio: 9 / 16;}


/** For the demo : **/
body {
  display:flex;
  flex-wrap:wrap;
  align-items:flex-start;
}
div {
  background: teal;
  width: 23%;
  margin:1%;
  padding:20px 0;
  box-sizing: border-box;
  color:#fff;
  text-align:center;
}
<div class="ar-1-1">aspect-ratio: 1 / 1;</div>
<div class="ar-3-2">aspect-ratio: 3 / 2;</div>
<div class="ar-4-3">aspect-ratio: 4 / 3;</div>
<div class="ar-16-9">aspect-ratio: 16 / 9;</div>
<div class="ar-2-3">aspect-ratio: 2 / 3;</div>
<div class="ar-3-4">aspect-ratio: 3 / 4;</div>
<div class="ar-9-16">aspect-ratio: 9 / 16;</div>

사용법 2. 사용방법vw 삭제:

하시면 됩니다.vw요소의 폭과 높이 모두에 대한 단위입니다.이렇게 하면 뷰포트 너비를 기준으로 요소의 가로 세로 비율을 유지할 수 있습니다.

vw : 뷰포트 폭의 100분의 1[MDN]

외에 '하다'를 사용할 .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

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

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>

다음은 데모를 사용한 Feeling이며, 다음은 수직수평 중심의 콘텐츠를 사용하여 응답성 높은 사각 그리드를 만드는 솔루션입니다.


vh/vw 유닛에 대한 브라우저 지원은 IE9 이상입니다.자세한 내용은 canIuse를 참조하십시오.

하다를 사용하세요.aspect-ratioCSS 성 c

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

이 문제에 대한 현명한 해결책이라고 생각되는 것을 우연히 발견했습니다.<svg> ★★★★★★★★★★★★★★★★★」display:grid.

A display:grid하면, 「자녀」를 해, 2명 그 과 같은 할 수 .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>원하는 비율: s의 비율:

  • <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 및 the the the 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>는 기본적으로 가변 높이의 기준선에 배치되는 치환된 요소가 됩니다(4px으로 ★★★★★★★★★★★★★★★★」3.5px(Firefox서서 ().는 베이스라인의 에 따라 .line-height에 ' 수 없다'를 설정해야 line-height: 0정확한 비율을 얻기 위해 의사 값을 구합니다.자세한 것은 이쪽.


저는 개인적으로 이 버전을 선호합니다.<svg>의 클래스(1개의 클래스를 수 마크업에 됩니다..ratio(필요한 개별 비율별로 클래스를 갖는 것이 아니라) 다양한 비율의 컨테이너를 취급합니다.

CSS를 사용하여 방법을 찾았습니다만, 자신의 웹 사이트의 흐름에 따라 달라질 수 있으므로 주의해 주십시오.웹 사이트의 유동적인 폭 부분에 일정한 가로 세로 비율의 비디오를 삽입하기 위해 이 작업을 수행했습니다.

예를 들어 다음과 같은 비디오가 내장되어 있다고 합시다.

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

그런 다음 이 모든 것을 "비디오" 클래스가 있는 div 안에 넣을 수 있습니다.이 비디오 클래스는 웹 사이트의 유동적인 요소가 될 수 있으므로 그 자체로는 직접적인 높이 제한이 없지만 브라우저 크기를 조정하면 웹 사이트의 흐름에 따라 폭이 달라집니다.이것은 아마도 비디오의 특정 애스펙트비를 유지하면서 임베디드 비디오를 도입하려고 하는 요소일 것입니다.

그러기 위해서, 「비디오」클래스 div내의 삽입 오브젝트 앞에 이미지를 둡니다.

!!! 중요한 것은, 이미지의 애스펙트비가 올바른 것을 유지하는 것입니다.또, 이미지의 사이즈는, 레이아웃에 근거해 얻을 수 있는 비디오(또는 A.R.를 유지하고 있는 것)의 최소 사이즈인 것을 확인해 주세요.이것에 의해, 퍼센티지 사이즈 변경시의 이미지의 해상도에 잠재적인 문제가 발생하지 않게 됩니다.예를 들어 석면비를 3:2로 유지하려면 3px x 2px 이미지만 사용하지 마십시오.상황에 따라서는 효과가 있을지도 모르지만, 아직 테스트해 본 적이 없기 때문에 피하는 것이 좋을지도 모릅니다.

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

나는 완전히 투명한 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%로 강제함으로써 비디오 클래스 요소에 있는 다른 요소를 최대한 활용하도록 지시합니다.

꽤 멋지죠?

자신의 디자인으로 동작시키기 위해서 조금 가지고 놀아야 할 수도 있지만, 저는 의외로 잘 동작하고 있습니다.일반적인 개념은 거기에 있습니다.

엘리엇이 이 해결책에 영감을 주었습니다.감사합니다.

aspectratio.png완전 투과적인 PNG 파일로, 우선 애스펙트 비율(내 경우는 30x10 픽셀)의 사이즈를 가지고 있습니다.

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는 target-module과 함께 동작하지 않을 수 있는 css3-module입니다.상호 운용성을 확인할 수 있습니다(예: caniuse.com).

@ @web-tiki를 사용하는 있기 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.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));
}

의 비율은, 9/16 의 사전 가 필요 .100:56.25 ★★★★★★★★★★★★★★★★★」100:75먼저 높이를 폭과 높이를 바꾸면 됩니다.height:100vh;width: calc(100vh * 9 / 16)9시 16분입니다.

다른 화면 크기에 맞게 조정하려면

  • 배경 크기의 커버/커버
    • 위 스타일은 너비: 높이 비율에 따라 포함과 유사합니다.
  • 오브젝트 핏
    • img/비디오 태그 커버/커버
  • @media (orientation: portrait)/@media (orientation: landscape)
    • :portrait/landscape비율을 변경합니다.

여기 w3schools.com에 기재되어 있는 바와 같이, 이 받아들여진 답변에서도 약간 반복되어, 값을 퍼센티지로 채웁니다(내 것을 포함).

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

Ergo는 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에서의 데모

에 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;
}

것을 미디어 에 따라 다른 할 수 됩니다.<img>(배경 이미지로서의 로고를 올바른 석면비로 투명한 .png로 설정합니다).Web_Designer는 http를 사용합니다.

CSS 를 합니다.aspect-ratio

https://caniuse.com/ #search=syslog-filename

https://web.dev/https-backets/

사용방법에 관심이 있는 경우 아래 초간단한 예를 참조하십시오.

.yourClass {
   aspect-ratio: 4/3;
}

다음은 web_designer의 답변에 대한 개선 사항입니다.

  • 래퍼 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>

svg를 사용할 수 있습니다.용기/랩퍼 위치를 상대적으로 만들고, 먼저 svg를 정적인 위치로 배치한 다음 절대 위치 컨텐츠(위: 0; 왼쪽: 0; 오른쪽: 0; 아래쪽: 0;)를 넣습니다.

16:9 비율의 예제:

image.src: (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%;" />

방법은 다음과 같습니다.

[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>

원천

귀사의 솔루션을 바탕으로 몇 가지 트릭을 만들었습니다.

사용 시 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(jQuery)

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

이것을 있으면 를 설정하기만 .data-keep-ratio높이/폭에 맞추면 끝입니다.

그리드 및 유사 요소 채우기 사용

나는 이 사건을 해결할 새로운 방법을 찾았다. 한 쪽의 입니다.padding-bottom단 한 가지 없이, , any any method method method method method method method method method method method method method method method method method method.position: absolute만, 사용방법display: grid;아, 아, 아, 아, 아, 아, 아, 네.

, 여기 있습니다..ratio::before을 간직하고padding-bottom: XX% ★★★★★★★★★★★★★★★★★」grid-area: 1 / 1 / 1 / 1;이는 의사 요소가 위치를 그리드에 유지하도록 강제합니다.에도 ★★★★★★★★★★★★★★★★★★★★★★★.width: 0; 방지()z-index★★★★★★★★★★★★★★★★★★★★★」

그리고 우리의 주요 요소는.ratio > *:first-child .ratio::before, 「」)grid-area: 1 / 1 / 1 / 1;둘 다 같은 그리드 셀 장소를 공유하고 있어요이제 임의의 콘텐츠를 div에 넣을 수 있습니다. 의사 요소는 폭/높이 비율을 결정하는 요소입니다.그리드 영역에 대한 자세한 정보

.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>


에 배치할 수 있지만 val을 사용하여 HTML에 할 수 .style★★★★★★★★★★★★★★★★★★★★★★★★★★★★★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>

대부분의 답변은 매우 쿨하지만 대부분의 답변은 이미 올바른 크기의 이미지가 필요합니다.다른 솔루션은 너비에서만 작동하며 사용 가능한 높이에 상관하지 않지만 컨텐츠를 특정 높이로 맞추려고 할 수도 있습니다.

휴대성과 사이징이 가능한 솔루션을 제공하기 위해 이들을 결합하려고 했습니다.이 트릭은 이미지의 자동 스케일링에 사용하지만 사전 렌더링된 이미지나 다른 형식의 두 번째 HTTP 요청을 사용하는 대신 인라인 svg 요소를 사용하는 것입니다.

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가 됩니다.

뷰 가로 뷰 중 하나의 한 한 큰 뷰 또는 에 아무것도 있지 않은 뷰포트)를 합니다.vw/vhportrait/landscape:

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

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

경우에 따라 다르지만, 어떤 경우에는 정말 쓸모가 있다.들면 - 을 설정할 수 .background-image된 유튜브를 하기 위해 합니다.<iframe>16:9 ★★★★★★★★★★★★★★★★★」position:absolutesyslog.

★★★의 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>

이 솔루션에서는img-태그가 특정 석면비를 채웁니다.사용할 수 없었습니다.backgroundCMS의 스타일 않습니다.<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>

캔버스 요소를 사용하여 가로 세로 비율을 유지하는 간단한 방법입니다.

동작하고 있는 것을 확인하려면 , 다음의 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>

2개의 div가 있다고 칩시다.outher div는 용기이고, inner는 비율을 유지하기 위해 필요한 요소(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 */
}

패딩은 %로 지정되면 높이가 아닌 폭에 따라 계산됩니다.따라서 기본적으로 높이가 어떻게 되든 상관없습니다.그 비율을 유지할 것입니다.

그냥 아이디어나 해킹일 뿐이야

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>

저는 이 문제에 꽤 많이 부딪혔기 때문에 JS 솔루션을 만들었습니다.기본적으로 지정한 비율에 따라 요소의 너비에 따라 domElement 높이가 조정됩니다.다음과 같이 사용할 수 있습니다.

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

는 '요소의 높이를 설정하다'가하시기 바랍니다.display:block ★★★★★★★★★★★★★★★★★」display:inline-block.

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

새로운 가로 세로 비율 태그는 멋질 텐데, 내 디바의 위치가 엉망이야.래퍼 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>

폭: 100px 및 높이: 50px(예: 2:1)를 유지한다고 가정합니다. 다음 계산을 수행합니다.

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

Chrome 88에서 새롭게 등장하여 곧 다른 브라우저에서도 새로운 CSS 속성이 등장합니다.

가로 세로 비율 CSS 속성은 자동 크기 계산 및 기타 레이아웃 함수의 계산에 사용되는 상자의 우선 가로 세로 비율을 설정합니다.

CSS 트릭 기사

상세 정보

div {
  background: rebeccapurple;
  height:100px;
  margin:1em auto;
}

.square {
  aspect-ratio: 1 / 1;
  }
<div class="square">
  
</div>

에는 이에 새로운 .CSS 에 、 CSS 、 CSS 。aspect-ratio.

https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio

@supports (aspect-ratio: 1 / 1) {
  div {
    aspect-ratio: 16 / 9;
    background-color: orange;
  }  
}
<div style="width: 200px"></div>
<hr />
<div style="width: 400px"></div>
<hr />
<div style="height: 50px"></div>
<hr />
<div style="height: 10px"></div>

Chrome과 Edge는 V88부터 이를 완전히 지원했으며 Firefox는 V81(세트)부터 플래그를 사용하여 이를 지원하고 있습니다.layout.css.aspect-ratio.enabled로로 합니다.truein about:config)를 참조해 주세요.

호환성 정보에 대해서는, https://caniuse.com/mdn-css_properties_aspect-ratio 를 참조해 주세요.

이 문제를 다음과 같이 해결했습니다.

.square {
  width: 100%;
  max-height: 100%;
  aspect-ratio: 1;
  background: red;
  position: relative;
  margin: auto;
  top: 50%;
  transform: translateY(-50%);
}

https://jsfiddle.net/r1jL3oqa/1/ 를 참조해 주세요.

전체 폭을 차지하도록 크기를 조정한 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%);
}

도 분명 '%'라고 하면 '%'를 풀 수 있을 4:32:1.

나는 새로운 해결책을 사용했다.

.squares{
  width: 30vw
  height: 30vw

메인 애스펙트 대비

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

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

언급URL : https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css

반응형