html - 使用 CSS 保持 div 的纵横比

标签 html css responsive-design aspect-ratio

我想创建一个响应式 div,它可以随着窗口宽度的变化而改变它的宽度/高度。

是否有任何 CSS 规则允许高度根据宽度改变,同时保持其纵横比

我知道我可以通过 JavaScript 做到这一点,但我更愿意只使用 CSS。

div keeping aspect ratio according to width of window

最佳答案

只需创建一个包装器 <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)。

这依赖于填充的事实:

The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)

其他宽高比和 100% 宽度的底边距值:

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

在 div 中放置内容:

为了保持 div 的纵横比并防止其内容拉伸(stretch)它,您需要添加一个绝对定位的 child 并将其拉伸(stretch)到包装器的边缘:

div.stretchy-wrapper {
  position: relative;
}

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

Here's a demo和另一个更深入的 demo

关于html - 使用 CSS 保持 div 的纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143862/

相关文章:

javascript - 使用 jQuery 进行复选框选择的 MultiSelect 下拉菜单

html - 如何将文字环绕在图像周围?

html - 使用GWT和CSS,如何垂直翻转输入元素中偶数位置的所有字母?

css - 响应式 CSS 的无序列表不以 DIV 为中心?

html - CSS 媒体查询不能在同一个样式表中工作?

javascript 检查电话号码和地址是否为空白

html - Flexbox 粘性页脚 - 'Flex: 1' 无法填充高度

html - 为什么这个 HTML 不起作用?

jquery - 当下拉列表被附加时会创建微小的空间

flutter - 如何降低 Flutter expansionTile 的高度