gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 23:19:58 24 4
gpt4 key购买 nike

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

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

什么是正确的,纯 CSS,让元素大小与背景图像完全匹配的方法,这样图像首先占据 100% 的宽度,然后根据需要占据尽可能多的高度以适应原始方面比例?

这是 Playground :http://jsfiddle.net/e5ek812c/

最佳答案

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

解释

padding-top,当设置为百分比时,使用元素的宽度作为引用 (100%)。不同于高度

.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

关于html - 动态元素高度以匹配背景覆盖尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29086139/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com