How to set background-size to "cover", plus a little more in CSS?

This is an old thread but I found a solution to this so thought I'd share.

Using background-size: auto 110%; doesn't really work because you lose the cover functionality. For responsive and more dynamic elements, you can end up with undesired blank spaces.

Instead, create a wrapping div with position:relative; overflow:hidden;. Then within that create your background div with position:absolute; and some additional settings. See below.

.banner-wrapper {
  position: relative;
  min-height: 340px;
  width: 100%;
  overflow: hidden;
  border: 1px solid #ccc;
}

.banner {
  position: absolute;
  left: -40px;
  right: -40px;
  top: -40px;
  bottom: -40px;
  width: calc(100% + 40px);
  background: url(https://upload.wikimedia.org/wikipedia/commons/2/25/Lang%27s_short_tail_blue_%28Leptotes_pirithous%29_male_underside.jpg) center center no-repeat;
  background-size: cover;
}
<div class="banner-wrapper">
  <div class="banner">
  </div>
</div>  

Simply using background-size: auto 110%; did the trick.


Example hover cover background https://codepen.io/Guirec/pen/VbxaMq?editors=1100

html

<div class="container">
  <div class="image zoom-in">
    <span>Zoom in</span>
  </div>
  <div class="image zoom-out">
    <span>Zoom out</span>
  </div>
</div>

css

.image {
  position: relative;
  overflow: hidden;
  background-color: #000;
  background-image: url("https://unsplash.it/700/400/?random");
  background-position: center center;
  background-size: cover;
  background-repeat: no-repeat;
  border: 1px solid #000;

  span {
    position: relative;
    z-index: 1;
  }
}

.zoom-in,
.zoom-out {
  &::after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: inherit;
    background-size: cover;
    transform-origin: center;
    transition: transform 0.4s ease-in-out;
  }
}

.zoom-in {
  &:focus,
  &:hover {
    &::after {
      transform: scale(1.05);
    }
  }
}

.zoom-out {
  &::after {
    transform: scale(1.05);
  }

  &:focus,
  &:hover {
    &::after {
      transform: scale(1);
    }
  }
}

/* Nothing interesting  */
.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  margin: 2vw;
  font-family: sans-serif;
  font-size: 4vw;
  color: #fff;
  text-shadow: 1px 1px 1px black;

  @media (min-width: 768px) {
    flex-direction: row;
  }
}

.image {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40vw;
  height: 25vw;
  margin: 2vw;

  &:nth-child(2n) {
    background-image: url("https://unsplash.it/700/400/?random=2");
  }
}

Tags:

Html

Css