与纯css的响应宽高比:如何填充容器的高度?

时间:2017-11-15 18:42:14

标签: html css css3 responsive-design

我有一个div(带有类容器的div),它具有固定高度(应该是动态的,事先不知道),它包含另一个div(具有类固定宽高比的那个)。

我希望内部div能够填充容器的高度,同时保持1:1的固定宽高比。

实现固定宽高比的常用技巧是利用填充:事实上,当为填充声明百分比而不是固定值时,百分比是根据相关元素的宽度计算的,即使我们声明垂直填充顶部或填充底部等值。

如果你想填充容器的WIDTH,这会使padding成为一个很好的技巧,但如果你想填充容器的高度,则不行。

是否可以仅使用CSS实现它?没有javascript谢谢。

理想情况下,我希望将CSS单元与视口相互补充,但相对于容器而言。类似的东西:

  • cw(容器宽度)
  • ch(容器高度)
  • cmin(容器分钟)
  • cmax(容器最大)

会吓人的。

<!DOCTYPE html>
<html>

<head>
  <style>
    .container {
      background-color: green;
      height: 30vh;
    }
    
    .fixed-aspect-ratio {
      background-color: red;
      width: 100%;
      padding-top: 100%;
      /* 1:1 Aspect Ratio */
      position: relative;
      /* If you want text inside of it */
    }
    /* If you want text inside of the container */
    
    .text {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="fixed-aspect-ratio">
      <div class="text">Some text</div>
      <!-- If you want text inside the container -->
    </div>
  </div>
</body>

</html>

https://www.w3schools.com/code/tryit.asp?filename=FLJBS4J2MTWS

2 个答案:

答案 0 :(得分:1)

高度没有类似的CSS解决方案,宽度为padding-bottom

除了脚本之外,这里有一个我用过的技巧,我放置了一个img,带有一个数据URL SVG(也可能是一个Base64 png),以避免额外的往返服务器,有一个方形尺寸。

通过将其高度设置为100%,它将保持其父级,内联块,正方形,并使用visibility: hidden隐藏它。

Stack snippet

.container {
  background-color: green;
  height: 50vh;
}

.fixed-aspect-ratio {
  display: inline-block;
  background-color: red;
  height: 100%;
  position: relative;
}

.fixed-aspect-ratio img {
  display: block;
  height: 100%;
  visibility: hidden;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
}
<div class="container">
  <div class="fixed-aspect-ratio">
    <img src="data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='10'><rect width='10' height='10'/></svg>">
    <div class="text">Some text</div>
    <!-- If you want text inside the container -->
  </div>
</div>

答案 1 :(得分:0)

将高度设置为100%,将宽度设置为x%

<!DOCTYPE html>
<html>

<head>
  <style>
    .container {
      background-color: green;
      height: 30vh;
    }
    
    .fixed-aspect-ratio {
      background-color: red;
      height: 100%;
      width: 10%;
      /* 1:1 Aspect Ratio */
      position: relative;
      /* If you want text inside of it */
    }
    /* If you want text inside of the container */
    
    .text {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }
  </style>
</head>

<body>
  <div class="container">
    <div class="fixed-aspect-ratio">
      <div class="text">Some text</div>
      <!-- If you want text inside the container -->
    </div>
  </div>
</body>

</html>

相关问题