能否使用CSS calc()来计算宽度/高度比例?

14

这是我目前拥有的代码(它还不能工作):

HTML:

<div class="chi_display_header" style="background-image:url('http://localhost/.../header-dummy-small.png');"></div>

CSS:

.chi_display_header {
    background-size:contain;
    width:100%;
    min-height:100px;
    height:calc(1vw * 270 / 1280px);
    max-height:270px;
    max-width:1280px;
    margin:0 auto;
}

这是一张居中响应式背景图片-容器应具有可变宽度/高度,我不想使用jQuery。

已知属性:

比率:1280:270

最小高度:100像素

最大高度:270像素

最大宽度:1280像素

我尝试通过计算来神奇地计算出.chi_display_header的容器高度:

height = calc(CURRENT_SCREEN_WIDTH * 270 / 1280);

然而我的当前方法

height:calc(1vw * 270 / 1280px);

还没有效果。是否有CSS解决方案?


相关链接:https://dev59.com/u3I_5IYBdhLWcg3wK_zE - Aziz
4
100vw 表示的是全宽度,而不是 1vw。 - circusdei
@aziz - 有没有使用calc的解决方案? - Blackbam
@circusdei 对的.....也许它似乎几乎可以工作,但是使用background-size: cover时会有一点被裁剪掉。 - Blackbam
3个回答

11

解决方案(感谢评论):

.chi_display_header {
    background-size:cover;
    width:100%;
    min-height:100px;
    height:calc(100vw * 270.0 / 1280.0);
    max-height:270px;
    max-width:1280px;
    margin:0 auto;
}

3

我将Blackbam的解决方案应用于div放置在body中,而body的左右padding为15px的情况下。从计算出来的高度中减去总共的左右padding(30px),可以消除出现在div上下方的空白。

height:calc(100vw * aspect_ratio - 30px);

2

即使没有使用calc(),也可以实现这个效果。 padding(甚至-top-bottom)是相对于元素的宽度而言的,因此你可以通过以下方式达到相同的效果:

.chi_display_header {
    background-size: cover;
    width: 100%;
    min-width: 474px;
    max-width: 1280px;
    height: 0;
    padding-bottom: 21.09375%;
}

你也可以使用相对/绝对定位技巧在内部添加元素,使用内部的<div>,但是如果内容超过包含高度,事情就会开始变得混乱:

.chi_display_header {
    ...
    position: relative;
}

.chi_display_header .inner {
    position: absolute;
    top: 0; left: 0; right: 0;
    padding: 15px;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接