CSS值background-size: cover
将拉伸图像但保持其宽高比。但是,它只会拉伸它,直到最小的一侧达到父节点的同一侧的100%。
/* This is an image of 100px Wide x 50px Tall, so it'll
stretch to 100% of the window height and then scale the
width larger to retain its width-to-height ratio.
*/
body
{
background-image: url( "/images/test.png" );
background-size: cover;
background-position: center;
}
我想要的东西会覆盖一些更大的百分比,例如130%。 (我将在CSS关键帧动画中使用它来使背景图像增大/缩小)
我该怎么做?
答案 0 :(得分:4)
通过使用伪元素,你可以实现类似的东西
CSS动画的浏览器支持率为+ 90%:http://caniuse.com/#feat=css-animation
.bkg {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
}
.bkg::before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-image: url(http://lorempixel.com/500/400/nature/1);
background-size: cover;
background-position: center;
animation: growme 5s forwards;
}
@keyframes growme {
from {transform: scale(1);}
to {transform: scale(1.3);}
}

<div class="bkg"></div>
&#13;
成长和缩小
.bkg {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
}
.bkg::before {
content: '';
position: absolute;
left: -20%;
top: -20%;
width: 140%;
height: 140%;
background-image: url(http://lorempixel.com/500/400/nature/1);
background-size: cover;
background-position: center;
animation: shrinkme ease-in-out 10s infinite;
}
@keyframes shrinkme {
0% {transform: scale(1);}
50% {transform: scale(.72);}
100% {transform: scale(1);}
}
&#13;
<div class="bkg"></div>
&#13;
根据注释进行更新,其中一些浏览器会出现动画伪元素问题,而只需使用子元素。
.bkg {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
}
.bkg div {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-image: url(http://lorempixel.com/500/400/nature/1);
background-size: cover;
background-position: center;
animation: growme 5s forwards;
}
@keyframes growme {
from {transform: scale(1);}
to {transform: scale(1.3);}
}
&#13;
<div class="bkg"><div></div></div>
&#13;
答案 1 :(得分:1)
我之前通过将背景图像应用于伪元素(例如::之前绝对定位,并对其应用缩放变换)来完成此操作。