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

相关文章:

html - 为什么我的主图像不在 Chrome 的中心?

html - 在 Bootstrap 3 中禁用响应式网格的问题

css - 2 个 100% 的 div 彼此相邻

javascript - 使用绝对定位和 z-index 堆叠动态添加的图像

html - 如何左对齐和垂直对齐标题中的图像并使文本水平放置在 div 的中心

html - SVG 全宽,同时保持 img 比例

javascript - Jquery 数据表标题与正文不对齐

css - 图像的边框颜色在 Safari 上显示为红色

html - 动态 float 2列

html - 响应页面在表格中不起作用