需求: 导航栏,有的标题栏需要使用平行四边形 、 梯形, 三角形应用的场景也比较多(面试)
思想:
- 使用伪元素 覆盖 父元素, 将背景颜色添加在父元素的底部
- 设置index = - 1,让父元素的内容显示
平行四边形----导航栏
<!-- 平行四边形 -->
<div class="keith">
<ul>
<li>博客园</li>
<li>首页</li>
<li>新随笔</li>
<li>联系</li>
<li>订阅</li>
<li>管理</li>
</ul>
</div>
<div class="triangle1">三角形</div>
<div class="triangle2">梯形</div>
// 样式
.keith ul {
padding: 0 7px;
box-sizing: border-box;
width: 100%;
overflow: hidden;
display: flex;
justify-content: space-between;
align-content: center;
.keith li {
margin: 5px 5px 0 8px;
margin-left: 2px;
position: relative;
width: 100px;
height: 30px;
line-height: 30px;
float: left;
text-align: center;
}
.keith li::after {
content: "";
position: absolute;
left: 0;
right: 0;
bottom: 0;
top: 0;
z-index: -1;
background: #2175bc;
-moz-transform: skewX(-25deg);
-ms-transform: skewX(-25deg);
-webkit-transform: skewX(-25deg);
transform: skewX(-25deg);
}
.keith li:hover::after {
background: #2586d7;
}
.keith li:hover {
color: white;
}
}
三角形
- 利用border的四个方向进行设置, 必须设置width和height的值为0
- 利用css3的属性clip-path 裁剪(0,0 位置为左上角)
// 方法1: 利用border
.triangle1 {
width: 0;
height: 0;
border-top: 50px solid transparent;
border-bottom: 50px solid deeppink; // 此时显示底部的三角形,其他为透明
border-left: 50px solid transparent;
border-right: 50px solid transparent;
}
···
tips: 如果不设置为透明,可以看到上下左右有四个三角形
// 方法2: 利用clip-path
.triangle1 {
width: 320px;
height: 60px;
background: pink; // 下面两个属性也可以在伪元素中设置
-webkit-clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
}
梯形
- 在三角形的基础上利用绝对定位,以及图形层级(z-index)来控制
- 使用css3属性clip-path
// 方法1
.triangle2 {
position: relative;
width: 0;
height: 0;
border-top: 50px solid transparent;
border-bottom: 50px solid deeppink; // 此时显示底部的三角形,其他为透明
border-left: 50px solid transparent;
border-right: 50px solid transparent;
&::before {
content: '';
position: absolute;
top: 0;
left: -20px;
width: 80px; // 使用一个白色的盒子覆盖它
height: 20px;
background: #fff;
}
}
// 方法2
.triangle2 {
width: 320px;
height: 60px;
line-height: 60px;
position: relative;
text-align: center;
&::after {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
z-index: -1; // 可以展示梯形中的字, 父元素不会被盖住
background: red;
-webkit-clip-path: polygon(0% 0%, 100% 0%, 80% 100%, 20% 100%);
}
&:hover {
color: white;
}
&:hover::after {
background: pink;
}
}
```