简体   繁体   中英

Dynamic element height to match background cover dimensions

I'm using the following CSS to set a cover background image on an element:

.bg {
    background: url(images/kitteh1.jpg) no-repeat;
    background-size: cover;
    background-position: center;
    height: 200px;
}

What is the right, CSS-only, way of having the element size exactly match that of the background image, such that the image first takes up 100% width, and then takes as much height as necessary to fit the original aspect ratio?

Here's the playground: http://jsfiddle.net/e5ek812c/

As far as I know, the CSS will never be aware of the image size. What you can do, however, is set a padding-top or padding-bottom to the image's ratio (height is 56.25% of the width here).

Explanation

padding-top , when set as a percentage, uses the element's width as a reference ( 100% ). Unlike height .

 .a { background-color: #ddd; } .bg { background: url(https://prinzhorn.github.io/skrollr/examples/images/kitteh1.jpg) no-repeat; background-size: cover; background-position: center; padding-top: 56.25%; } .c { background-color: #aaa; } 
 <div class="a">hello</div> <div class="bg"></div> <div class="c">bye</div> 

Updated JS Fiddle

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