【问题标题】:Keep content div aspect ratio with fixed height header使用固定高度标题保持内容 div 纵横比
【发布时间】:2015-07-23 23:54:22
【问题描述】:

我正在尝试创建一个固定比例为 4:3 的图像幻灯片,以 80 像素的固定高度标题填充网站上的整个视口。我怎样才能做到这一点?

This question 非常接近,但缺少固定标头。

有什么帮助吗?

布局应该是:

 -------------------------------------      -
| Header: height = 80px, width = 100% |     |
 -------------------------------------      |
    |          Main div           |         > Total height = 100%
    |      Fixed ratio = 4:3      |         |
    |          Centered           |         |
     -----------------------------          -


|------------------v------------------|
           Total width = 100%

【问题讨论】:

    标签: html css aspect-ratio


    【解决方案1】:

    下面的 CSS 可以解决问题:

    body {
        margin: 0;
        padding: 0;
    }
    header {
        width: 100vw;
        height: 80px;
        background: red;
    }
    article {
        /* Get the height based on the available space (100 height - 80px) */
        height: calc(100vmin - 80px);
        /* Get the width based on the available space and aspect ratio (height /3 * 4) */
        width: calc((100vmin - 80px) / 3 * 4);
        margin: 0px auto;
        background: blue;
    }
    <header></header><article></article>

    使用calc,我们可以很容易地确定我们的底框有height100% - 80pxcalc(100vmin - 80px)。从那里,我们可以使用相同的计算来计算对象的width。我使用vmin 来解释纵向屏幕上的行为。

    【讨论】:

    • 感谢您的意见。这确实有效,除非窗口高度大于宽度,在这种情况下它会溢出 div 而不是将其全部显示在视图中。
    • @fseixas 我已经修改它以使用vmin,它通过给我视口的高度和宽度之间的最小公分母来解决这个问题。
    • 这确实改善了它,在这种情况下它现在正在调整高度,但左侧仍有一些溢出,即宽度>vw。
    • 嗯,我明白你的意思了。您可以在此时添加一个max-width,并说它不应该比100%(或100vw)宽,即使它实际上是作弊。
    • 是的,但是虽然该作弊可以防止溢出,但它不会保持纵横比。
    猜你喜欢
    • 2015-12-02
    • 1970-01-01
    • 2013-07-07
    • 2017-02-13
    • 2014-12-13
    • 2012-06-02
    • 2019-06-29
    • 2015-10-26
    相关资源
    最近更新 更多