p { font-size: 18px; line-height: 1.5; margin-bottom: 20px; } pre { background-color: #f7f7f7; padding: 10px; } .box { position: relative; width: 100px; height: 100px; background-color: #eee; margin-bottom: 20px; } .box:before { content: "before"; position: absolute; top: 0; left: 0; background-color: #ff9b8e; color: #fff; padding: 5px; } .box:after { content: "after"; position: absolute; bottom: 0; right: 0; background-color: #8ec4ff; color: #fff; padding: 5px; }
::before和::after是CSS中的伪元素,它们可以用于在HTML元素的前后插入内容。这些内容可以是文字、图像、装饰性的元素或其它任何支持的元素。
下面是一个示例,使用::before和::after在一个方框中分别添加了两个文本内容:
.box:before {
content: "before";
position: absolute;
top: 0;
left: 0;
background-color: #ff9b8e;
color: #fff;
padding: 5px;
}
.box:after {
content: "after";
position: absolute;
bottom: 0;
right: 0;
background-color: #8ec4ff;
color: #fff;
padding: 5px;
}
<div class="box"></div> 在这个例子中,使用::before和::after在方框的前后分别添加了两个文本内容,它们的样式通过CSS定义。需要注意的是,content属性的值是必须设置的,否则::before和::after将不会产生任何内容。
除了添加内容,::before和::after还可以用于绘制一些简单的图形和装饰性元素。下面是另一个示例,使用::before和::after在一个按钮的前后添加了两个箭头:
.button:before {
content: "";
display: inline-block;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-left: 8px solid #007bff;
margin-right: 10px;
}
.button:after {
content: "";
display: inline-block;
border-top: 5px solid transparent;
border-bottom: 5px solid transparent;
border-right: 8px solid #007bff;
margin-left: 10px;
}
<button class="button">click me</button> click me在这个例子中,使用::before和::after分别绘制了两个箭头,它们的样式同样通过CSS定义。需要注意的是,这里使用了一个空的content属性,并将其设置为display:inline-block,这样才能让它们在行内显示。
总之,::before和::after是非常实用的CSS伪元素,可以用于添加内容、图形和装饰性元素等。需要注意的是,在使用时应该合理控制它们的样式和位置,避免影响到页面布局和可访问性。