sourcetip

div 크기 유지 종횡비 응답적으로 변경

fileupload 2023. 9. 25. 22:54
반응형

div 크기 유지 종횡비 응답적으로 변경

이미지에 너비 또는 높이만 지정하면 가로/세로 비율을 유지하며 증가/축소됩니다. 하지만 다른 요소와 동일한 효과를 원하는 경우에는 비율을 사용하여 너비와 높이를 함께 묶을 수 있습니까?

이것은 자바스크립트가 필요 없이 순수 CSS를 사용하여 할 수 있습니다.이는 백분율이 포함된 블록의 너비 상대적이라는 (다소 직관적이지 않은) 사실을 활용합니다.예는 다음과 같습니다.

.wrapper {
  width: 50%;
  /* whatever width you want */
  display: inline-block;
  position: relative;
}
.wrapper:after {
  padding-top: 56.25%;
  /* 16:9 ratio */
  display: block;
  content: '';
}
.main {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  /* fill parent */
  background-color: deepskyblue;
  /* let's see it! */
  color: white;
}
<div class="wrapper">
  <div class="main">
    This is your div with the specified aspect ratio.
  </div>
</div>

Chris의 생각을 뒤엎고, 당신이 절대적으로 위치한 내부 요소를 사용할 필요가 없도록 의사 요소를 사용하는 것이 또 다른 선택입니다.

<style>
.square {
    /* width within the parent.
       can be any percentage. */
    width: 100%;
}
.square:before {
    content: "";
    float: left;

    /* essentially the aspect ratio. 100% means the
       div will remain 100% as tall as it is wide, or
       square in other words.  */
    padding-bottom: 100%;
}
/* this is a clearfix. you can use whatever
   clearfix you usually use, add
   overflow:hidden to the parent element,
   or simply float the parent container. */
.square:after {
    content: "";
    display: table;
    clear: both;
}
</style>
<div class="square">
  <h1>Square</h1>
  <p>This div will maintain its aspect ratio.</p>
</div>

여기 데모를 준비했습니다. http://codepen.io/tcmulder/pen/iqnDr


편집:

이제 아이작의 아이디어에서 벗어나 현대 브라우저에서는 단순히 vw 유닛을 사용하여 가로 세로 비율을 강제하는 것이 더 쉽습니다(저도 vh를 그처럼 사용하지 않을 것이거나 창 높이에 따라 가로 비율이 변경되지 않을 것입니다).

이를 통해 다음과 같은 작업을 간소화할 수 있습니다.

<style>
.square {
    /* width within the parent (could use vw instead of course) */
    width: 50%;
    /* set aspect ratio */
    height: 50vw;
}
</style>
<div class="square">
  <h1>Square</h1>
  <p>This div will maintain its aspect ratio.</p>
</div>

수정된 데모를 만들어 보았습니다. https://codepen.io/tcmulder/pen/MdojRG?editors=1100

컨테이너가 아닌 브라우저의 너비를 기반으로 하며 무한히 증가/축소되므로 터무니없이 크거나 작지 않도록 하려면 최대 높이, 최대 너비 및/또는 최소 높이, 최소 너비를 설정할 수도 있습니다.

또한 글꼴 크기를 vw 측정으로 설정하고 모든 inner to em 측정으로 설정하면 요소 내부의 내용을 확장할 수 있습니다. 여기 이에 대한 데모가 있습니다. https://codepen.io/tcmulder/pen/VBJqLV?editors=1100

<style>
#aspectRatio
{
  position:fixed;
  left:0px;
  top:0px;
  width:60vw;
  height:40vw;
  border:1px solid;
  font-size:10vw;
}
</style>
<body>
<div id="aspectRatio">Aspect Ratio?</div>
</body>

여기서 주목할 점은.vw= 포트 너비 보기 및vh= 뷰포트 높이

그것이 내 해결책입니다.

<div class="main" style="width: 100%;">
    <div class="container">
        <div class="sizing"></div>
        <div class="content"></div>
    </div>
</div>

.main {
    width: 100%;
}
.container {
    width: 30%;
    float: right;
    position: relative;
}
.sizing {
    width: 100%;
    padding-bottom: 50%;
    visibility: hidden;
}
.content {
    width: 100%;
    height: 100%;
    background-color: red;
    position: absolute;
    margin-top: -50%;
}

http://jsfiddle.net/aG4Fs/3/

(function( $ ) {
  $.fn.keepRatio = function(which) {
      var $this = $(this);
      var w = $this.width();
      var h = $this.height();
      var ratio = w/h;
      $(window).resize(function() {
          switch(which) {
              case 'width':
                  var nh = $this.width() / ratio;
                  $this.css('height', nh + 'px');
                  break;
              case 'height':
                  var nw = $this.height() * ratio;
                  $this.css('width', nw + 'px');
                  break;
          }
      });

  }
})( jQuery );      

$(document).ready(function(){
    $('#foo').keepRatio('width');
});

작동 예: http://jsfiddle.net/QtftX/1/

언급URL : https://stackoverflow.com/questions/12121090/responsively-change-div-size-keeping-aspect-ratio

반응형