动态元素高度以匹配背景覆盖尺寸

Dynamic element height to match background cover dimensions

我正在使用以下 CSS 在元素上设置封面背景图片:

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

什么是正确的,仅 CSS,使元素大小与背景图像完全匹配的方法,这样图像首先占据 100% 的宽度,然后占据与背景图像一样多的高度需要适应原始宽高比吗?

这里是游乐场:http://jsfiddle.net/e5ek812c/

据我所知,CSS 永远不会知道图像大小。 然而,你可以做的是将 padding-toppadding-bottom 设置为图像的比例(这里的高度是宽度的 56.25%)。

说明

padding-top,当设置为百分比时,使用元素的宽度作为参考 (100%)。不像 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