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

相关文章:

javascript - PHP 如何不缓存生成的 HTML 但缓存图像/js/css 等静态数据

jquery - 我第一次点击 jquery 移动页面会添加溢出 :hidden on body tag

javascript - 带有 css/js 的 Django 'Include' 模板

php - 恢复多个输入数据

html - 未应用溢出的嵌套 flexbox 中的 CSS

javascript - 如何创建以js为段落的垂直制表符?

html - 第一个 CSS 动画完成后如何播放第二个 CSS 动画

javascript - 如何在网页中显示模态对话框?

css - 响应式 Logo - 菜单重叠 Logo

html - 在小屏幕上以更多行重新排列 div