(CSS) skew img frame without distorting image

2019-06-05 02:13发布

I'm making a website that contains many skewed elements, like this:

enter image description here

This isn't too bad, there are CSS transforms that could skew it. But how about this:

enter image description here

The image isn't distorted, just the frame is cropped in a skewed way. What's the easiest/best way to do this?

标签: html css skew
2条回答
一夜七次
2楼-- · 2019-06-05 02:58

I ended up using the following. It creates a skewed parent, then unskews the child, centering it and making it big enough to fill the skew's stick-out bits.

HTML

<div class="skewed">
  <img src="images/sad-kid.jpg">
</div>

CSS

div.skewed {
  position: relative;
  height: 140px;
  transform: skew(-2deg) rotate(2deg);
  -webkit-transform: skew(-2deg) rotate(2deg);
  -moz-transform: skew(-2deg) rotate(2deg);
  overflow: hidden;
}

div.skewed > * {
  width: 110%;
  position: absolute;
  top: 50%;
  transform: skew(2deg) rotate(-2deg) translateY(-50%);
  -webkit-transform: skew(2deg) rotate(-2deg) translateY(-50%);
  -moz-transform: skew(2deg) rotate(-2deg) translateY(-50%);
}

OUTPUT

enter image description here

This is similar to Andy Hoffman's method, but supports a greater number of browsers.

查看更多
一纸荒年 Trace。
3楼-- · 2019-06-05 03:09

I think this should work for you. As a Mark commented on, clip-path is a nice way to go. There are tools for getting just the right path such as Clippy. Once you've got the path, you drop it right into your code. In my demo, I used it on the div wrapping the image, rather than on the image itself. I did it this way to keep border effects—added via pseudo-class—on top of the image.

enter image description here

Demo: http://codepen.io/antibland/pen/eZKxNa

查看更多
登录 后发表回答