Is it possible to use CSS calc() in order to calculate an width/height ratio?

Blackbam picture Blackbam · May 4, 2016 · Viewed 30.9k times · Source

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?

Answer

Blackbam picture Blackbam · May 5, 2016

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;
}