How to create images in CSS with slanted borders

5.5k views Asked by At

What I am going for

What I am trying to achieve

I have an image, that needs to appear inside a polygon. The hot pink area is the image.

What I have tried

Using SVG triangle shapes (100% wide) that are laid on top and bottom of the image. Top-left triangle on top and bottom-left at the bottom.

It works great but there seems to be rendering issues on many browsers where you see a random line around the SVG. (see image below, could be a separate question by itself)

enter image description here

I have also tried using skewed/rotated elements on top and bottom. But since the element is responsive, on certain resolution, the skewed elements create gaps. (see image below)

enter image description here

What I could try

Using images. Many problems there. It would be my last resort. Images are not resolution independent, I would have to use huge images for the slants to look good on high dpi screens, which would have to be scaled down in browsers, all not good.

Where I need help

Looking for any other way I could achieve this effect, preferably CSS based solution.

1

There are 1 answers

9
Persijn On

SVG

I used the polygon shape i created your slanted image.
Using patterns i created a background image that can fill the shape.

Setting the fill to an URL with the pattern ID created the shape.

.slanted {
  width: 50vw;
  height: auto;
}

.shape {
  fill: url(#img1);
}
<svg class="slanted" viewbox="-1 -1 102 102" preserveAspectRatio="none">
  <defs>
    <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
      <image xlink:href="http://lorempixel.com/g/400/200/" x="0" y="0" width="150" height="100" />
    </pattern>
  </defs>
  <polygon class="shape" points="0,20 100,0 100,100, 0,80" />
</svg>


CSS

Using 3D transform you can pretty easily get this shape.
The image will also be rotated.
The perspective sets how deep the 3d effect is going to be.
While setting transform: rotate() sets how much its going to rotate.

.container {
  margin-top: 50px;
  perspective: 600px;
  width: 300px;
  height: 200px;
}

.shape {
  transform: rotateY(-45deg);
  width: 100%;
  height: 100%;
  background: url(http://lorempixel.com/g/400/200/);
}
<div class="container">
  <div class="shape"></div>
</div>