首页 > 解决方案 > 带角度的 CSS 菱形 (120, 60, 120, 60)

问题描述

是否可以使用纯 CSS 创建一个 120 度和 60 度相反角度的菱形形状?

菱形图像

标签: csscss-shapes

解决方案


带有渐变的简单背景,您可以使用元素的宽度/高度轻松调整以控制角度和尺寸:

.box {
  background:
   linear-gradient(to top right   ,orange 49.5%, transparent 50%) top right,
   linear-gradient(to top left    ,orange 49.5%, transparent 50%) top left,
   linear-gradient(to bottom right,orange 49.5%, transparent 50%) bottom right,
   linear-gradient(to bottom left ,orange 49.5%, transparent 50%) bottom left;
  background-size:50% 50%;
  background-repeat:no-repeat;
  
  width:260px;  /* 2*sin(120/2)*150 = 260 */
  height:150px; /* 2*sin(60/2)*150  = 150 OR 2*cos(120/2)*150  = 150*/
  display:inline-block;
  margin:5px;
}
<div class="box">
</div>
<div class="box" style="height:100px;">
</div>
<div class="box" style="width:200px;">
</div>

为确保角度相同,请考虑保持 div 的纵横比:

.box {
  background:
   linear-gradient(to top right   ,orange 49.5%, transparent 50%) top right,
   linear-gradient(to top left    ,orange 49.5%, transparent 50%) top left,
   linear-gradient(to bottom right,orange 49.5%, transparent 50%) bottom right,
   linear-gradient(to bottom left ,orange 49.5%, transparent 50%) bottom left;
  background-size:50% 50%;
  background-repeat:no-repeat;
  
  width:260px;  
  display:inline-block;
  margin:5px;
}

/* 2*sin(120/2)*h = w 
   h = w / (sin(60)*2)
   h = w * 0.57736
*/
.box:before {
  content:"";
  display:block;
  padding-top:57.73%;
}
<div class="box">
</div>
<div class="box" style="width:150px;">
</div>
<div class="box" style="width:80px;">
</div>

CSS 菱形

相同的想法,但与clip-path

.box {
  background:orange;
  clip-path:polygon(0 50%, 50% 100%,100% 50%,50% 0);
  width:260px;  
  display:inline-block;
  margin:5px;
}

/* 2*sin(120/2)*h = w 
   h = w / (sin(60)*2)
   h = w * 0.57736
*/
.box:before {
  content:"";
  display:block;
  padding-top:57.73%;
}
<div class="box">
</div>
<div class="box" style="width:150px;">
</div>
<div class="box" style="width:80px;">
</div>

如果你想要一些边框,你可以调整渐变:

.box {
  --g:var(--c,orange) calc(49.5% - 3px),#000 calc(49.5% - 2px),#000 49.5%, transparent 50%;
  background:
   linear-gradient(to top right   ,var(--g)) top right,
   linear-gradient(to top left    ,var(--g)) top left,
   linear-gradient(to bottom right,var(--g)) bottom right,
   linear-gradient(to bottom left ,var(--g)) bottom left;
  background-size:50% 50%;
  background-repeat:no-repeat;
  
  width:260px; 
  display:inline-block;
  margin:5px;
}

/* 2*sin(120/2)*h = w 
   h = w / (sin(60)*2)
   h = w * 0.57736
*/
.box:before {
  content:"";
  display:block;
  padding-top:57.73%;
}
<div class="box">
</div>
<div class="box" style="--c:transparent;">
</div>

CSS菱形带边框


推荐阅读