如何使用CSS制作关键形状?

时间:2015-01-02 02:32:54

标签: css css-shapes

我想创建一个包含shaple的html div:enter image description here

在html表格中使用一些服装css,我可以在一列上创建一个带有圆形化身的表格,并在另一列中使用矩形框,但不能使圆圈与上面的图片重叠。

欣赏你的提示。

1 个答案:

答案 0 :(得分:6)

您可以使用:pseudo-element来执行此操作。

div {
  position: relative;
  width: 300px;
  height: 75px;
  background: #B0B4FF;
  margin: 25px 0;
}
div:after {
  position: absolute;
  content: '';
  width: 125px;
  height: 125px;
  border-radius: 50%;
  background: url(http://www.lorempixel.com/125/125);
  top: -25px;
  right: -25px;
}
<div></div>


您可以通过JavaScript更改background-image

JavaScript代码将遍历样式表规则,找到#info:after的规则并将其backgroundImage更改为指定的规则。

var ss = document.styleSheets;

for (i = 0; i < ss.length; i++) {
  var rules = ss[i];
  for (j = 0; j < rules.cssRules.length; j++) {
    var r = rules.cssRules[j];
    if (r.selectorText == "#info:after" || r.selectorText == "#info::after") {
      r.style.backgroundImage = 'url(http://dummyimage.com/125/125/0f8d94/0011ff&text=newImage)'
    }
  }
}
#info {
  position: relative;
  width: 300px;
  height: 75px;
  background: #B0B4FF;
  margin: 25px 0;
}
#info:after {
  position: absolute;
  content: '';
  width: 125px;
  height: 125px;
  border-radius: 50%;
  background: url(http://www.lorempixel.com/125/125);
  top: -25px;
  right: -25px;
}
<div id="info"></div>


由于您无法通过CSS更改background-image,因此您需要img标记,因为:伪元素不适用于img标记,您将会必须使用另一个div作为矩形。

.container {
  position: relative;
  width: 325px;
}
.info {
  width: 300px;
  height: 75px;
  background: #B0B4FF;
  margin: 25px 0;
  text-align: center;
  line-height: 75px;
}
img {
  position: absolute;
  top: -25px;
  right: -25px;
  width: 125px;
  height: 125px;
  border-radius: 50%;
  background: url(http://www.lorempixel.com/125/125);
}
<div class="container">
  <div class="info">Info Text</div>
  <img src="http://lorempixel.com/125/125" />
</div>


满足标题, A Real Key Shape

enter image description here

#container {
  width: 325px;
}
<div id="container">
  <svg viewBox="-2 -2 206 103">
    <defs>
      <clipPath id="circ">
        <rect id="rect" x="1" y="1" width="98" height="98" rx="100" />
      </clipPath>
    </defs>
    <path d="M0,50 a50,50 0 0,1 96.9846,-17.101 m-96.9846,17.101 a50,50 0 0,0 96.9846,17.101 l10,10 q5,3 6,-3 v-12.5 h12.5 l7,7 l10,-12 l10,12 h7 l10,-12 l7,7 h8 l16,-15.5 q5,0 -16,-10 h-71.5 v-12.5 q0,-6 -6,-3 l-10,10" stroke-linecap="round" stroke="saddlebrown"
    stroke-width="2" fill="tan" />
    <path d="M100,51 h97 l-1.5,2 h-85z" stroke="saddlebrown" stroke-width="1" fill="none" />
    <text x="110" y="48" font-size="6">Info Text</text>
    <image clip-path="url(#circ)" width="98" height="98" x="1" y="1" style=" width: 100px; height: 100px; border-radius: 50%;" xlink:href="http://dummyimage.com/150x150/a77243/000000&text=Real Key Shape" />
  </svg>
</div>