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/58725912/

相关文章:

javascript - 在页面加载之间闪烁

javascript - Meteor: react 性更改之间集合项目的 UI 缓动

html - 如何只垂直包裹一个div?

css - 是否可以在 HTML5 输入类型 ="date"元素上设置默认占位符文本的样式?在 Chrome ?

html - 将文本与复选框对齐

html - 不同设备浏览器上的通用字体

jquery - 带有全宽图像的 Bootstrap 导航栏附加

javascript - Colorbox scalePhotos 不工作

c# - Telerik TopPane 高度自动?

html - Bootstrap 中的 float div