有没有办法在CSS中创建这样的东西,但更灵活(例如在CSS Grid单元格中使用)? - 原始帖子here。
#triangles {
margin: 3em;
width: 0; /* set dimensions of DIV to 0 so borders collapse and touch */
height: 0;
border-color: red blue green yellow; /* top, right, bottom, and left border */
border-style: solid;
border-width: 50px; /* width of each border */
}

<div id="triangles"></div>
&#13;
答案 0 :(得分:3)
您可以使用linear-gradient
轻松创建这些三角形。您可以考虑单独的类(如下所示)或在一个元素中将它们用作多个背景。
#triangles {
width: 100px;
height: 100px;
display: inline-block;
}
#triangles div {
height: 100%;
}
.tr-left {
background:
linear-gradient(to top left, transparent 50%, red 0) 0 100%/50% 50% no-repeat,
linear-gradient(to bottom left, transparent 50%, red 0) 0 0/50% 50% no-repeat;
}
.tr-right {
background:
linear-gradient(to top right, transparent 50%, yellow 0) 100% 100%/50% 50% no-repeat,
linear-gradient(to bottom right, transparent 50%, yellow 0) 100% 0/50% 50% no-repeat;
}
.tr-top {
background:
linear-gradient(to top right, transparent 50%, green 0) 0 0/50% 50% no-repeat,
linear-gradient(to top left, transparent 50%, green 0) 100% 0/50% 50% no-repeat;
}
.tr-bottom {
background:
linear-gradient(to bottom right, transparent 50%, blue 0) 0 100%/50% 50% no-repeat,
linear-gradient(to bottom left, transparent 50%, blue 0) 100% 100%/50% 50% no-repeat;
}
<div id="triangles" class="tr-left"></div>
<div id="triangles" class="tr-left">
<div class="tr-right"></div>
</div>
<div id="triangles" class="tr-top">
<div class="tr-right"></div>
</div>
<div id="triangles" class="tr-left">
<div class="tr-bottom">
<div class="tr-top">
<div class="tr-right"></div>
</div>
</div>
</div>
答案 1 :(得分:3)
或者,您可以使用SVG。
快速jsfiddle。
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.container {
width: 100vw;
height: 100vh;
background-color: #F9F871;
}
.svg-box {
width: 30vw;
margin: 0 auto;
position: relative;
top: 50%;
transform: translateY(-50%);
}
.top {
fill: #845EC2;
}
.left {
fill: #D65DB1;
}
.bottom {
fill: #FF9671;
}
.right {
fill: #FFC75F;
}
<div class="container">
<div class="svg-box">
<svg class="triangle" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
<polygon class="top" points="0,0 100,0 50,50"/>
<polygon class="left" points="0,0 50,50 0,100"/>
<polygon class="bottom" points="0,100 50,50 100,100"/>
<polygon class="right" points="100,0 100,100 50,50"/>
</svg>
</div>
</div>