Combine background size percentage, and background size cover

Here, I have some divs of various sizes, and I'm applying a background image to them:

div {
  border: solid 2px red; 
  background-image: url('https://www.360nobs.com/wp-content/uploads/2016/02/lady-gaga.jpg'); 
  background-size: cover; 
  background-repeat: no-repeat; 
  
  display: inline-block; 
  margin: 2em;   

}

.a {
  width: 100px; 
  height: 200px; 
}

.b {
  width: 200px; 
  height: 100px ; 
}

.c {
  width: 200px; 
  height: 200px; 
}
<div class ="a"> </div> 
<div class ="b"> </div> 
<div class ="c"> </div> 

Now, I only want to display the image on the left half of the div, but I want it to cover the full height. The background shouldn't warp, instead it should zoom/stretch.

One way to do this is to add position right on it:

div {
  border: solid 2px red; 
  background-image: url('https://www.360nobs.com/wp-content/uploads/2016/02/lady-gaga.jpg'); 
  background-size: cover; 
  background-repeat: no-repeat; 
  
  display: inline-block; 
  margin: 2em;   

 background-position: top right 50px; //Actually in my situation I would just use vw; 

}

.a {
  width: 100px; 
  height: 200px; 
}

.b {
  width: 200px; 
  height: 100px ; 
}

.c {
  width: 200px; 
  height: 200px; 
}
<div class ="a"> </div> 
<div class ="b"> </div> 
<div class ="c"> </div> 

But the problem with this is that it only shows the right hand side of the image, whereas in my scenario I want it to either show from the left, or show from the center.

Is there a way to apply a clip to the background image? My alternative solution is to lay a div on top to hide it.

2 answers

  • answered 2018-11-08 06:58 JL Barcelona

    you can try to add background-attachment:fixed; to your background. hope it works.

  • answered 2018-11-08 14:39 Temani Afif

    I would consider a pseudo element that will be your background layer:

    .box {
      border: solid 2px red;
      background-image: url('https://www.360nobs.com/wp-content/uploads/2016/02/lady-gaga.jpg');
      background-size: 0 0;
      display: inline-block;
      margin: 2em;
      position: relative;
    }
    .box:before {
      content:"";
      position:absolute;
      top:0;
      left:0;
      right:50%;
      bottom:0;
      background-image:inherit;
      background-size:cover;
    }
    
    .a {
      width: 100px;
      height: 200px;
    }
    
    .b {
      width: 200px;
      height: 100px;
    }
    
    .c {
      width: 200px;
      height: 200px;
    }
    <div class="a box"> </div>
    <div class="b box"> </div>
    <div class="c box"> </div>