How to implement an pure-CSS flag-shape container?

与世无争的帅哥 提交于 2019-12-12 05:26:19

问题


My target is to implement a pure-CSS flag-shape container like this:

Requirements include:

  • background-color of parent container is unknown
  • works for different line-height and font-size settings

回答1:


Option 1

Use clip-path, but check browser support for this property:

div {
  clip-path: polygon(0% 0%, 100% 0%, 85% 50%, 100% 100%, 0% 100%);
  
  background-color: #ff69b4;

  /* styles for demo */
  padding: 20px;
  color: #fff;
}
<div>5 items</div>

Option 2

Use SVG:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
  <polygon points="0 0, 100 0, 85 50, 100 100, 0 100" fill="#ff69b4" />
</svg>

Option 3

Use absolutely positioned pseudoelements with gradients (to simulate triangles)

div {
  background-color: #ff69b4;
  margin-right: 50px;
  position: relative;

  /* styles for demo */
  padding: 20px;
  color: #fff;
}

/* pseudoelement to simulate triangles */
div:before,
div:after {
  content: "";
  position: absolute;
  top: 0;
  left: 100%;
  width: 50px;
  height: 50%;
  background-image: linear-gradient(to left top, transparent 50%, #ff69b4 50%);
}

/* Flip triangle */
div:after {
  top: 50%;
  transform: scaleY(-1);
}
<div>5 items</div>



回答2:


Another possible variant would be to use transformed pseudo elements.

  • Create 2 layers using ::before ad ::after pseudo elements.
  • Add background-color and place them with position: absolute having 50% height of the parent.
  • Apply CSS3 skew() transformations to get the flag shape.

Output Image:

Working Demo:

* {box-sizing: border-box;}
body {
  background: linear-gradient(green, yellow) no-repeat;
  min-height: 100vh;
  padding: 10px;
  margin: 0;
}
.flag {
  padding: 5px 40px 5px 10px;
  display: inline-block;
  vertical-align: top;
  position: relative;
  line-height: 40px;
  overflow: hidden;
}

.flag:before,
.flag:after {
  transform-origin: top right;
  transform: skewX(-45deg);
  position: absolute;
  background: pink;
  content: '';
  left: -45px;
  height: 50%;
  z-index: -1;
  right: 0;
  top: 0;
}

.flag:after {
  transform-origin: bottom right;
  transform: skewX(45deg);
  top: auto;
  bottom: 0;
}
<div class="flag">5 Items</div>


来源:https://stackoverflow.com/questions/45528862/how-to-implement-an-pure-css-flag-shape-container

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!