div的两个边缘不同地倾斜

时间:2018-09-26 14:05:46

标签: html5 css3

这是我要实现的目标:

倾斜的div:

enter image description here

HTML:

<span class="container">
    <span class="element">some dummy text</span>
</span>

CSS:

.container .element {
  font-size: 24px;
  background-color: gray;
  padding: 5px;
  position: relative; 
  }
  .container .element:before {
    content: " ";
    position: absolute;
    display: block;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
    background: gray;
    transform-origin: bottom left;
    -ms-transform: skew(-20deg, 0deg);
    -webkit-transform: skew(-20deg, 0deg);
    transform: skew(-20deg, 0deg); 
    }
  .container .element:after {
    content: " ";
    position: absolute;
    display: block;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
    background: gray;
    transform-origin: bottom left;
    -ms-transform: skew(0deg, -1deg);
    -webkit-transform: skew(0deg, -1deg);
    transform: skew(0deg, -1deg); 
    }

https://jsfiddle.net/mktcany9/

即使有很多有关类似div的话题,我也无法真正做到像图片上那样。

1 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助。

transform origin属性允许伪元素从右下角倾斜,并且溢出的部分用overflow:hidden;隐藏。

div {
  position: relative;
  display: inline-block;
  padding: 1em 5em 1em 1em;
  overflow: hidden;
  color: #fff;
}

div:after {
  -webkit-transform-origin: 100% 0;
  -ms-transform-origin: 100% 0;
  transform-origin: 100% 0;
  -webkit-transform: skew(-45deg);
  -ms-transform: skew(-45deg);
  transform: skew(-45deg);
  z-index: -1;
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
}

body {
  background: #fff;
}
<div>slanted div text</div>
<div>
  slanted div text<br/> on several lines<br/> an other line
</div>
<div>wider slanted div text with more text inside</div>