Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

calc

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?

like image 461
Blackbam Avatar asked May 04 '16 20:05

Blackbam


2 Answers

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;
}
like image 164
rgchris Avatar answered Oct 31 '22 22:10

rgchris


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;
}
like image 34
Blackbam Avatar answered Oct 31 '22 22:10

Blackbam