Is it possible to cut specific parts of an image?

2019-07-11 06:50发布

问题:

Sometimes images just explain things better than 1000 words

assumed the black border is my image I want to cut off the top left/right edge - like marked by the red lines.

Would it be possible (if yes: how) to cut an image this way with CSS?

Just in case its not clear what I mean by cut: I want

By cut I mean, that the image will look like this

回答1:

Without using a wrapper element, you can use clip-path, though the support isn't great.

img.cut {
  -webkit-clip-path: polygon(50px 0, calc(100% - 50px) 0, 100% 50px, 100% 100%, 0 100%, 0 50px);
  clip-path: polygon(50px 0, calc(100% - 50px) 0, 100% 50px, 100% 100%, 0 100%, 0 50px);
}
<img class="cut" src="http://lorempixel.com/200/300/">

This uses calc (widely supported), so you can specify exact pixel values to clip by.



回答2:

CSS Pseudo

If you know you're background is going to remain a solid colour, you can achieve this using pseudo elements in a number of ways.

1st option

A very simple solution is to use the pseudo elements with borders to which should get you the effect you want.

div {
  height: 300px;
  background: red;
  position: relative;
}
div:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  border-top: 80px solid white;
  border-right: 80px solid red;
  width: 0;
}
div:after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  border-top: 80px solid white;
  border-left: 80px solid red;
  width: 0;
}
<div></div>


2nd Option

Using a single pseudo element which is larger than the parent and rotating it to get the desired effect.

This is a much cleaner effect and also means the use of background images is supported and easier to implement.

div {
  height: 200px;
  width: 200px;
  background: transparent;
  position: relative;
  z-index: 9;
  overflow: hidden;
}
div:before {
  content: '';
  width: 200%;
  height: 200%;
  position: absolute;
  transform: rotate(45deg);
  background: red;
  left: -50%;
  top: 20px;
<div></div>