首页 文章

根据高度保持div纵横比

提问于
浏览
23

我需要将元素的 width 维持为 height 的百分比 . 因此,随着高度的变化,宽度会更新 .

相反的情况可以通过使用填充顶部的%值来实现,但填充左边的百分比将是对象宽度的百分比,而不是其高度 .

所以使用这样的标记:

<div class="box">
  <div class="inner"></div>
</div>

我想用这样的东西:

.box {
    position: absolute;
    margin-top: 50%;
    bottom: 0;
}
.inner {
    padding-left: 200%;
}

确保框的 aspect ratio is maintained according to it's height . 高度是流动的,因为它的高度变化,盒子的高度也会变高 .

我知道如何用JavaScript实现这一点,只是想知道是否有一个干净的CSS解决方案?

4 回答

  • 15

    您可以使用具有所需比例的图像来帮助进行比例尺寸调整(可以通过将一个尺寸设置为某个值而将其他尺寸设置为自动来按比例缩放图像) . 图像不一定是可见的,但它必须占据空间 .

    .box {
      position: absolute;
      bottom: 0;
      left: 0;
      height: 50%;
    }
    .size-helper {
      display: block;
      width: auto;
      height: 100%;
    }
    .inner {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(255, 255, 153, .8);
    }
    
    <div class="box">
      <img class="size-helper" src="//dummyimage.com/200x100/999/000" width="200" height="100">
      <div class="inner">
        1. box has fluid height<br>
        2. img has 2:1 aspect ratio, 100% height, auto width, static position<br>
        2.1 it thus maintains width = 200% of height<br>
        2.2 it defines the dimensions of the box<br>
        3. inner expands as much as box
      </div>
    </div>
    

    在上面的例子中,box,inner和helper都是相同的大小 .

  • 5

    您可以对元素的高度和宽度使用vh单位,因此它们都是 change according to the viewport height .

    vh视口高度的1/100 . (MDN)

    DEMO

    .box {
        position: absolute;
        height:50vh;
        width:100vh;
        bottom: 0;
        background:teal;
    }
    
    <div class="box"></div>
    
  • 0

    你写的CSS技巧非常适合在一个元素上保持比例 width / height . 它基于 padding 属性,当其值为百分比时,与父宽度成比例,即使对于 padding-toppadding-bottom 也是如此 .

    没有CSS属性可以设置与父高度成比例的水平大小 . 所以我认为没有干净的CSS解决方案 .

  • 24

    我可以't find a pure CSS solution. Here'使用CSS Element Queries JavaScript库的解决方案 .

    var aspectRatio = 16/9;
    var element = document.querySelector('.center');
    function update() {
      element.style.width = (element.clientHeight * aspectRatio) + 'px';
    }
    
    new ResizeSensor(element, update);
    update();
    

    CodePen demo!

相关问题