是否可以使用 CSS calc() 来计算宽高比?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37037732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to use CSS calc() in order to calculate an width/height ratio?
提问by Blackbam
This is the code which I currently have (it does not work yet):
这是我目前拥有的代码(它还不起作用):
HTML:
HTML:
<div class="chi_display_header" style="background-image:url('http://localhost/.../header-dummy-small.png');"></div>
CSS:
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;
}
This is a centered responsive background image - the container should have a variable width / height and I do not want to use jQuery.
这是一个居中的响应式背景图像 - 容器应该具有可变的宽度/高度,我不想使用 jQuery。
Known properties:
已知属性:
Ratio: 1280:270
Minimum height: 100px
Maximum height: 270px
Maximum width: 1280px
比率:1280:270
最小高度:100px
最大高度:270px
最大宽度:1280px
What I try to do is to calculate the container height of .chi_display_header magically with calc:
我尝试做的是用 calc 神奇地计算 .chi_display_header 的容器高度:
height = calc( CURRENT_SCREEN_WIDTH * 270 / 1280);
高度 = calc( CURRENT_SCREEN_WIDTH * 270 / 1280);
However my current approach
但是我目前的方法
height:calc(1vw * 270 / 1280px);
does not work yet. Is there a CSS solution?
还不行。有没有 CSS 解决方案?
采纳答案by Blackbam
Solution (ty 4 comments):
解决方案(ty 4条评论):
.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;
}
回答by LJaeren
I applied Blackbam's solution to the situation where a div was placed in the body and the body had left and right padding of 15px. Subtracting the total left and right padding (30px) from the calculated height removed white-space that appeared above and below the div.
我将 Blackbam 的解决方案应用于在 body 中放置一个 div 并且 body 具有 15px 的左右填充的情况。从计算的高度中减去总的左右内边距 (30px) 可以去除出现在 div 上方和下方的空白区域。
height:calc(100vw * aspect_ratio - 30px);
回答by rgchris
It's possible to do this without calc()
as well. padding
(even -top
and -bottom
) are relative to the element's width, so you can get the same effect thus:
也可以在没有的情况下做到这一点calc()
。padding
(even-top
和-bottom
) 相对于元素的宽度,因此您可以获得相同的效果:
.chi_display_header {
background-size: cover;
width: 100%;
min-width: 474px;
max-width: 1280px;
height: 0;
padding-bottom: 21.09375%;
}
You can also add elements inside with an inner <div>
using the relative/absolute trick, though things will begin to go awry if the content exceeds the containing height:
您还可以<div>
使用相对/绝对技巧在内部添加元素,但如果内容超过包含高度,事情就会开始出错:
.chi_display_header {
...
position: relative;
}
.chi_display_header .inner {
position: absolute;
top: 0; left: 0; right: 0;
padding: 15px;
}