给菜单的顶部添加一个小三角形
起因
最近在学习仿制百度首页。百度首页中有一个设置菜单很特别:由无序列表组成,但是外边框的上边缘有一个小三角。于是想做一个仿真的百度设置菜单。
制作
一切由border引起
如何用CSS画出直角三角形?以我当时的CSS知识水平,并没有接触到绘制直角三角形的技巧,直到一位学长的奇技淫巧点醒了我:
使用border!!!
于半懵半醒中,我围观了一波学长大佬的操作:
1.先建立一个边框为红色10px,宽高均为100px的box:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.triangle {
width: 100px;
height: 100px;
background-color: #0A83DD;
border: 10px solid red;
}
</style>
</head>
<body>
<div class="triangle"></div>
</body>
</html>
2.再将这个box的宽高等比例缩小,到10px:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.triangle {
width: 10px;
height: 10px;
background-color: #0A83DD;
border: 10px solid red;
}
</style>
</head>
<body>
<div class="triangle"></div>
</body>
</html>
3.我们可以发现,宽高缩小,而border仍然没有改变,这时候四个边框变成了梯形,由此得出:当宽高为零时,我们就能得到四个直角三角形组成的正方形,于是,通过控制其他三个边框的颜色为transparent
,就能得到我们想要的三角形。
实现
有了上一节的基础,我们可以开始编写一个菜单:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.settingLists {
border: 1px solid #ccc;
border-radius: 3px;
width: 70px;
padding: 0;
position: relative;
}
.settingLists li {
float: none !important;
height: 16px;
padding: .2em;
margin: .1em !important;
line-height: 16px;
text-align: center;
list-style-type: none;
}
.settingLists li:hover {
background: #3388ff;
color: #fff;
}
.settingLists li:hover a {
color: #fff;
}
.settingLists li a:hover {
color: #fff;
}
.settingLists li a {
display: inline-block;
height: 16px;
text-decoration: none;
color: #2b2b2b;
display: block;
line-height: 16px;
position: relative;
margin: 2px auto;
}
.settingLists::before{
content: “”;
width: 0;
height: 0;
border: 6px solid transparent;
border-bottom-color: #ccc;
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -3px;
}
</style>
</head>
<body>
<div class="settingLists">
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
</div>
</body>
</html>
通过伪元素::before
,将三角形固定在菜单的顶部,效果图如下:
如果进一步美化,可以将三角形中间的灰色去掉,思路是,再用一个小点儿的白色三角形盖住三角形的中间和底边:
.settingLists::after {
content: "";
width: 0;
height: 0;
border: 4px solid transparent;
border-bottom-color: #fff;
position: absolute;
bottom: 100%;
left: 50%;
margin-left: -1px;
}
通过伪元素::after
,将另一个小三角形固定在大三角形上面:
到目前为止,这个菜单的外形就基本完成了。