Is there any way to make background image resize itself to the clip-path set for the element in css?

194 Views Asked by At

I want my background-image to follow the shape of its element. Like if I set my element's clip-path to: clip-path: polygon(0 0, 50% 10%, 50% 90%, 0% 100%); I want the background-image to change its size and aspect-ratio to match the element's clip-path.

Everything I try crops the background image instead of reshaping, stretching or squeezing it..

1

There are 1 best solutions below

0
G-Cyrillus On

You may use background-size and eventually set some coordonates of your clip-path into css var() so it can be used by background-size:

here an example from your clip-path

html {
  background:green;
  --clipRight: 50%;/* value setting how far from left you clip the element */
}
body {
  margin:0;
  min-height:100vh;/* min-height because demo has no content to fill and stretch body */
  clip-path: polygon(0 0, var(--clipRight) 10%, var(--clipRight) 90%, 0% 100%); 
  background:url(https://dummyimage.com/300)  0 0 / var(--clipRight) 100% no-repeat yellow;
}

Note that you might also need to set a different background to html and body to be sure your resized image is drawn on body and not transfered and drawn on html.