Is it possible to use CSS calc() in order to calculate an width/height ratio?
Solution 1
Solution (ty 4 comments):
.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;
}
Solution 2
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.
height:calc(100vw * aspect_ratio - 30px);
Solution 3
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:
.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:
.chi_display_header {
...
position: relative;
}
.chi_display_header .inner {
position: absolute;
top: 0; left: 0; right: 0;
padding: 15px;
}
Blackbam
Hello! My name is David. I have studied Software Engineering & Internet Computing at the Vienna University of Technology. I am a passionate lead developer, enterprise software engineer and senior web developer. Are you looking for a smart, creative and open-minded IT professional who loves new challenges? Hire me! Especially for complex high-quality Symfony, Laravel, Pimcore or WordPress projects. Be free to contact me via my website or Stack Overflow Careers. Author of a useful general purpose PHP toolkit.
Updated on January 10, 2020Comments
-
Blackbam over 4 years
This is the code which I currently have (it does not work yet):
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; }
This is a centered responsive background image - the container should have a variable width / height and I do not want to use jQuery.
Known properties:
Ratio: 1280:270
Minimum height: 100px
Maximum height: 270px
Maximum width: 1280px
What I try to do is to calculate the container height of .chi_display_header magically with calc:
height = calc( CURRENT_SCREEN_WIDTH * 270 / 1280);
However my current approach
height:calc(1vw * 270 / 1280px);
does not work yet. Is there a CSS solution?