Search code examples
cssbackground-imagecss-transformsskew

How to change rotate background-image, if block is styled by "skew"


I have some problem and, I think this problem will not have solved. [Style and code bottom] enter image description here

.box-blog {
  background: url(../img/image.png) center no-repeat;
  background-size: cver;
  width: 80%;
  display: block;
  margin: 0 auto;
  margin-top: 71px;
  height: 192px;
  border-radius: 0 40px;
  -webkit-transform: skew(20deg);
  -moz-transform: skew(20deg);
  -o-transform: skew(20deg);
  background-color: #333;
  box-shadow: 15px 0 0 rgba(248,48,46,.3);
}`

Solution

  • A common solution is to use pseudo-element for the background image and create the inverse skew on it :

    .box-blog {
      position: relative;
      width: 80%;
      display: block;
      margin: 0 auto;
      margin-top: 71px;
      height: 192px;
      border-radius: 0 40px;
      transform: skew(20deg);
      background-color: #333;
      box-shadow: 15px 0 0 rgba(248, 48, 46, .3);
      overflow: hidden;
    }
    
    .box-blog:before {
      content: " ";
      background: url(https://lorempixel.com/400/400/) center no-repeat;
      background-size: cover;
      position: absolute;
      top: 0;
      right: -40px;
      bottom: 0;
      left: -40px;
      transform: skew(-20deg);
    }
    <div class="box-blog">
    
    </div>

    This can be a generic solution for any kind of tranformation and you have two situations :

    • Transform the element without transforming the background : you transform the element and you create the inverse tranformation on the pseudo-element like we did
    • Transform the background without transforming the element : you simply add the transformation to the pseudo-element.

    You need also to becarefull about any overflow issue.