简体   繁体   中英

CSS: auto calc height of element to match the background-image

I want a section of my site (banner) to be an image that fit all width and for the image to maintain the full width (not the px width, but in percentage) at all times. I don't care about the height being too low, I need the image to always show all the width content and the height to be auto.

I'm using background-size: contain and this keeps the full width of the image but the height needs to be calculated, because then the container height will be higher than the image's. I've tried using viewport units but it's not consistent between different resolutions (maybe I'm doing it wrong but the value for a higher resolution doesn't work for a lower one).

How would I make this responsive?

The markup:

<body>
    <section class="feat-bottom">
        <h4>some title</h4>
    </section>
</body>

I'm using CSS for this image because, as we all (should) know, design images don't belong in the markup. So the image has to fit all the width, what would be the difference between 100% and 100vw? The first one is the parent's width, body has all the width in the screen and the second is the (again?) the device's width?

Will this approach be compatible with tablets and phones? Should I use a second image optimized for these cases?

To calculate the height of the element I'm using a formula that calculates the height while maintaining the aspect ratio:

New height = New width / (Original width / Original height)

So translating this into css gives:

section.feat-bottom {
    height: calc(100vw / (1920px / 800px))
}

This approach offers a fluid scaling, so no break points needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM