Don Rhummy Don Rhummy - 10 days ago 6
CSS Question

Is there a way to use CSS to make a background image act like "cover" but at 120%?

The CSS value

background-size: cover
will stretch an image but retain its width to height ratio. However, it will only stretch it until the smallest side reaches 100% of the parent node's same side.

/* 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;
}


I want something that will do a cover but to some larger percentage, for example 130%. (I will be using this in a CSS keyframes animation to make the background image grow/shrink)

How would I do this?

Answer

By using a pseudo element you can achieve something like that

CSS animation has a browser support at +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>

Grow and shrink

.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>

Update based on comment where some browsers have issues animation pseudo elements, where one simply use a child element instead.

.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>