矩形菱形 HTML & CSS3

Diamond in rectangle HTML & CSS3

我想在矩形中制作钻石。我已经用正方形做了:

.box {
  width:100px;
  height:100px;
  background:orange;
  z-index:1;
  position:relative;  
}

.box:before {
  position:absolute;
  content:'';
  width:70.71%;
  height:70.71%;
  transform: rotate(45deg);
  background: red;
  top: 15%;
  left: 15%;
}
<div class="box"></div>

但我想做成这样:

矩形是响应式的,因此它的大小永远不会相同。有什么想法吗?

非常感谢

您正在尝试通过修改矩形来创建菱形。如果您尝试使用纸矩形,您就会明白这不是最简单的方法。

您可以使用 clip-path:

.diamond {
  background-color: #eee;
  -webkit-clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
          clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
  margin: 0 auto;
  text-align: center;
  padding: 2rem;
}
<div class="diamond">I'm a diamond</div>

...剩下你要做的就是设置它的宽度、高度(或 min-* / max-* 中的任何一个)以响应地控制它的比例。

请注意 CSS clip-path 目前只有约 88% 的活跃浏览器 supported 最明显缺乏 IE 和 Edge 的支持。

如果您需要这些支持,唯一的方法是使用两层包装器并从这些包装器的 ::before::after 伪造物构建大纲。

此方法使用了两个三角形,这些三角形使用 CSS border.

生成

我认为您不能将 % 用于 border 宽度,因此我改为使用视口单位。

.box {
  width: 50vw;
  height: 25vw;
  background: orange;
  z-index: 1;
  position: relative;
}

.box:before,
.box:after {
  content: '';
  position: absolute;
  width: 0;
  height: 0;
}

.box:before {
  border-right: solid 25vw red;
  border-top: solid 12.5vw transparent;
  border-bottom: solid 12.5vw transparent;
}

.box:after {
  right: 0;
  border-left: solid 25vw red;
  border-top: solid 12.5vw transparent;
  border-bottom: solid 12.5vw transparent;
}
<div class="box"></div>