how to set a shape to a div

2019-08-04 09:34发布

I would like to set a shape to a div tag. Everything works fine, but when I set an img tag inside that shape, it does not show well.

My CSS code :

#chevron{
  width: 350px;
  height: 100px;
  background: #337AB7;
  border-radius: 10px 10px 0 0;
  position: relative;
}
#chevron:before { 
  content: ''; 
  position: absolute;
  top: 20px; 
  left: 0;
  height: 100%;
  width: 51%;
  background: #337AB7;
  -webkit-transform: skew(0deg, 6deg);    -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg); }

#chevron:after { 
  content: ''; 
  position: absolute;
  top: 20px; 
  right: 0;
  height: 100%;
  width: 50%;
  background: #337AB7;
  -webkit-transform: skew(0deg, -6deg); -moz-transform: skew(0deg, -6deg); -ms-transform: skew(0deg, -6deg); -o-transform: skew(0deg, -6deg); transform: skew(0deg, -6deg); }

My html file :

<div id="chevron">
  <img  src="http://i.stack.imgur.com/HtYUn.jpg" style="width:120px;height:120px"/>
</div>

I want to set my shape (chevron) as a background and the inner elements should be over it.

http://jsfiddle.net/45tyb219/2/

2条回答
放我归山
2楼-- · 2019-08-04 10:22

Just add position: relative; and z-index: 1; to your .img - alternatively you can also add z-index: -1; to the #chevron:after.

#chevron{
  width: 350px;
  height: 100px;
  background: #337AB7;
  border-radius: 10px 10px 0 0;
  position: relative;
}
#chevron:before { 
  content: ''; 
  position: absolute;
  top: 20px; 
  left: 0;
  height: 100%;
  width: 51%;
  background: #337AB7;
  -webkit-transform: skew(0deg, 6deg);    -moz-transform: skew(0deg, 6deg);
  -ms-transform: skew(0deg, 6deg);
  -o-transform: skew(0deg, 6deg);
  transform: skew(0deg, 6deg); }

#chevron:after { 
  content: ''; 
  position: absolute;
  top: 20px; 
  right: 0;
  height: 100%;
  width: 50%;
  background: #337AB7;
  -webkit-transform: skew(0deg, -6deg); -moz-transform: skew(0deg, -6deg); -ms-transform: skew(0deg, -6deg); -o-transform: skew(0deg, -6deg); transform: skew(0deg, -6deg); }

img {
    position: relative;
    z-index: 1;
}
<div id="chevron">
  <img  src="http://i.stack.imgur.com/HtYUn.jpg" style="margin-left: 100px;width:120px;height:120px"/>
</div>

查看更多
家丑人穷心不美
3楼-- · 2019-08-04 10:24

You can achieve this with CSS but SVG makes it much easier :

svg{width:50%;display:block;margin:0 auto;}
<svg viewbox="0 0 100 50">
  <defs>
    <pattern id="img" patternUnits="userSpaceOnUse" width="100" height="50">
      <image xlink:href="http://i.imgur.com/5NK0H1e.jpg" x="0" y="0" height="50" width="100" />
    </pattern>
  </defs>
  <path fill="url(#img)" d="M5 0 H95 Q100 0 100 5 V45 L50 50 L0 45 V5 Q0 0 5 0z" />
</svg>

In this demo, the image is set in the <pattern> element and used to fill the shape defined with the <path /> element.

查看更多
登录 后发表回答