简体   繁体   English

动态元素高度以匹配背景封面尺寸

[英]Dynamic element height to match background cover dimensions

I'm using the following CSS to set a cover background image on an element: 我正在使用以下CSS在元素上设置封面背景图片:

.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? 什么是使CSS元素尺寸与背景图像完全匹配的正确方法(仅CSS),以便图像首先占据100%的宽度,然后占据所需的高度以适合原始长宽比?

Here's the playground: http://jsfiddle.net/e5ek812c/ 这是操场: http : //jsfiddle.net/e5ek812c/

As far as I know, the CSS will never be aware of the image size. 据我所知,CSS永远不会意识到图像的大小。 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). 但是,您可以将图像的比例设置为padding-toppadding-bottom (高度为宽度的56.25% )。

Explanation 说明

padding-top , when set as a percentage, uses the element's width as a reference ( 100% ). padding-top设置为百分比时,将元素的宽度用作参考( 100% )。 Unlike height . 不同于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 更新了JS小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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