css - 带角度的 CSS 菱形 (120, 60, 120, 60)
问题描述
是否可以使用纯 CSS 创建一个 120 度和 60 度相反角度的菱形形状?
解决方案
带有渐变的简单背景,您可以使用元素的宽度/高度轻松调整以控制角度和尺寸:
.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>
相同的想法,但与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>
推荐阅读
- event-handling - 光滑网格;自己处理单元格中元素的鼠标悬停/悬停事件
- c - scanf(" "); 是什么意思 双引号之间只有一个空格?
- html - 通过 attr 进行 Angular 属性绑定。使用@Attribute 时产生空值
- css - 如何制作这样的css动画?
- c++ - 如何为 Visual Studio 禁用 servicehub.identityhost
- dart - http请求中的int到双重转换
- sql - 重新生成丢失的身份价值
- json - 如何阻止“PDF、JSON 和 Dockerfiles”在浏览器中打开下载按钮
- java - @RolesAllowed 干扰 @RequestMapping
- jwplayer - JW Player 字幕在视频暂停时加载