#基本使用
使用伪类 ::before 向前添加内容,使用 ::after 向后面添加内容。
伪类的应用场景比较多,一定要掌握,最下面通过应用实例讲解。
a::after {
content: " (坚持努力) ";
}
#提取属性
使用属性值添加内容,可以使用标准属性与自定义属性(一般用data-*表示,比如data-title=“标题”)。
<style>
a::after {
content: attr(href);
}
</style>
<a href="baidu.com">百度</a>
示例一:自定义提示框
代码:一定要使用自定义属性data-title,否则会出现两个提示框,一个默认,一个自定义。
<style>
body{
padding: 100px;
background: #ccc;
}
button{
position: relative;
}
button:hover::before{
content: "";
border:10px solid #fff;
border-left-color: transparent;
border-right-color: transparent;
border-top-color: transparent;
position: absolute;
top: 12px;
z-index: 1;
}
button:hover::after{
content: attr(data-title);
padding: 5px 10px;
background: #fff;
border: 1px solid #ddd;
position: absolute;
top: calc(100% + 10px);
left: 0;
width:max-content;
color: green;
}
</style>
<body>
<button data-title="这是自定义提示框">按钮</button>
</body>
示例二:
上面提示框有个缺陷,提示框的三角是白色背景,若弹窗后面的背景也是白色,那么三角就看不出来了。所以我们需要用两个三角覆盖在一起形成一个三角,来形成一个灰色边框。
div {
width: 300px;
height: 200px;
border: 1px solid #000;
position: relative;
}
div::before {
content: "";
border: 10px solid #000;
border-right-color: transparent;
border-left-color: transparent;
border-top-color: transparent;
position: absolute;
top: -20px;
left: 20px;
}
div::after {
content: "";
border: 9px solid #fff;
border-right-color: transparent;
border-left-color: transparent;
border-top-color: transparent;
position: absolute;
top: -18px;
left: 21px;
}
<body>
<div></div>
</body>