html - 有没有一种方法可以使用 CSS 使背景图像像 "cover"但在 120%?

标签 html css

CSS 值 background-size: cover 将拉伸(stretch)图像但保持其宽高比。但是,它只会拉伸(stretch)它,直到最小边达到父节点同一边的 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 关键帧动画中使用它来使背景图像增大/缩小)

我该怎么做?

最佳答案

通过使用伪元素你可以实现类似的东西

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>

增长和收缩

.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);}
}
<div class="bkg"></div>

根据一些浏览器存在动画伪元素问题的评论进行更新,其中一个简单地使用子元素代替。

.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);}  
}
<div class="bkg"><div></div></div>

关于html - 有没有一种方法可以使用 CSS 使背景图像像 "cover"但在 120%?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40853079/

相关文章:

java - 使用java获取主url

javascript - HTML 文本,为隐藏字段设置相同的值

javascript - html中的表单点击提交按钮时无法提交数据?

jquery - 旋转 180 度后将图像返回到原始位置

html - 我正在使用 “@media print” 打印我的 html 页面。在这里,我遇到了模型框不可见背景颜色的问题

html - 带有更大箭头的选项下拉按钮

javascript - 悬停幻灯片重新定位错误在 IE 中不起作用

css - 在 HTML,CSS 中更改鼠标悬停时的瓷砖颜色

jquery - 我们可以更改浏览器的 native 视频播放器的 css 吗?如果不是,那么最轻便的 html5 视频播放器插件是什么?

javascript - 如何检测网页中使用了哪一种定义的字体?