效果

html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
margin: 50px 100px;
}
.box {
width: 0;
height: 0;
border: 20px solid;
border-color: red yellow green blue;
}
.triRect {
width: 0;
height: 0;
border: 20px solid;
margin-top: 20px;
}
.triangle-up {
border-color: transparent transparent green;
}
.triangle-right {
border-color: transparent transparent transparent green;
}
.triangle-down {
border-color: green transparent transparent transparent;
}
.triangle-left {
border-color: transparent green transparent transparent;
}
.box-prompt {
position: relative;
width: 1000px;
height: 200px;
border: 1px solid #f0660a;
background: #fff;
border-radius: .3em;
margin-top: 20px;
}
.up::after {
content: "";
position: absolute;
background: inherit;
border: inherit;
top: -10px;
left: 25px;
padding: 9px;
border-right: 0;
border-bottom: 0;
transform: rotate(45deg);
}
.down::after {
content: "";
position: absolute;
background: inherit;
border: inherit;
bottom: -10px;
left: 25px;
padding: 9px;
border-top: 0;
border-right: 0;
transform: rotate(-45deg);
}
</style>
</head>
<body>
<div class="box">
</div>
<div class="triRect">
</div>
<div class=" triRect triangle-up">
</div>
<div class=" triRect triangle-right">
</div>
<div class=" triRect triangle-down">
</div>
<div class=" triRect triangle-left">
</div>
<div class="box-prompt up ">
</div>
<div class="box-prompt down">
</div>
</body>
</html>
问题
我们可以看到实现一个带三角箭头的提示框虽然简单,但它还存在一些隐藏的bug。请看下图:

由于伪类元素的背景色和父元素的背景色相同,当内容没有颜色时,看上去刚好。但若给内容加上一个背景色,就导致出现下三角空白的问题。
解决办法
1.当三角(小矩形)较小时,可以给里面的内容添加一个上外边距,让其刚好避开这个矩形;
.select>li:first-child{
margin-top: 5px;
}

可以看到,里面的元素和外部容器顶部边距为5px,刚好避开
2.当里面的内容有颜色时,设置三角(小矩形)的z-index = -1.
<script>
$(".select li:eq(0)").mouseenter(function(){
$(".tri").css("z-index","-1")
}).mouseleave(function(){
$(".tri").css("z-index","0")
})
</script>

可以看到,虽然里面的元素和外部容器顶部边距为0时,也不会出现下三角空白问题

被折叠的 条评论
为什么被折叠?



