如何才能达到与 background-size: cover;
相同的效果,但使用百分比值。
我试过了
background-size: auto 100%;
但这并不相似。现在你可能会问,为什么我不简单地使用 background-size: cover;
然后,这是因为我想为背景图像设置动画,而你不能从 设置动画覆盖
到 %
值。
非常感谢任何帮助。
最佳答案
百分比 + 自动在某些情况下有效,但并非全部。 cover
值自动将宽度或高度设置为 100%,以便其他尺寸适合或溢出容器,同时保持纵横比。使用 percentage + auto 你需要弄清楚哪一侧适合自己:
div {
display: inline-block;
background-position: center center;
background-repeat: no-repeat;
border: 1px solid #CCC;
}
.box-port {
width: 300px;
height: 150px;
}
.box-land {
width: 150px;
height: 300px;
}
.img-port {
background-image: url(http://dummyimage.com/400x200/CCC/000);
}
.img-land {
background-image: url(http://dummyimage.com/200x400/CCC/000);
}
.size-full-width {
background-size: 100% auto;
}
.size-full-height {
background-size: auto 100%;
}
<p>Using <code>background-size: auto 100%</code> for:</p>
<div class="img-port box-port size-full-height">portraint inside portrait (pass)</div>
<div class="img-land box-port size-full-height">landscape inside portrait (fail)</div>
<p>Using <code>background-size: 100% auto</code> for:</p>
<div class="img-port box-land size-full-width">portraint inside landscape (fail)</div>
<div class="img-land box-land size-full-width">landscape inside landscape (pass)</div>
我能想到的唯一解决方案是比较容器与背景图像的纵横比,然后使用 background-size: 100% auto
或 background-size : 自动 100%
。
关于html - 给背景大小 : cover effect via percentage value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27401023/