伪元素
- 伪元素不是独立的 HTML 元素,而是依附于某个已有的真实 HTML 元素。它的生命周期完全由父元素决定,父元素存在时才能渲染。
- 这个子元素不会出现在 DOM 中,但可以通过 CSS 样式进行控制。
::after
是一个 CSS 伪元素,用于在 HTML 元素的内容之后插入一个虚拟的子元素。
::after
的常见用途
- 添加装饰性内容(如图标、分隔线)。
- 构建复合形状(如箭头、对话框)。
- 动态内容添加(如标签、标记等)。
基本语法
selector::after {
content: 'string'; /* 必须指定内容,可以是文本、图片、空内容 */
display: block | inline | inline-block; /* 设置显示类型 */
position: relative | absolute; /* 常结合父元素定位 */
}
注意:
::after
必须设置content
属性,否则伪元素不会显示。
示例
示例结构
- 将相关css代码放在lc.css文件中
- lc.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>
<link rel="stylesheet" type="text/css" href="lc.css">
</head>
<body>
<div class="composite-shape"></div>
</body>
</html>
示例 1:在文本后插入装饰内容
<p class="composite-shape">Hello, world!</p>
.decorated::after {
content: ' ✨'; /* 添加内容 */
color: gold; /* 设置颜色 */
font-size: 1.5em; /* 调整大小 */
}
效果:
示例 2:动态组合长方形和半圆
.rectangle {
position: relative;
width: 200px;
height: 100px;
background-color: #4caf50; /* 长方形颜色 */
border-radius: 0; /* 长方形没有圆角 */
}
.rectangle::after {
content: '';
position: absolute;
bottom: -50px; /* 半圆拼接到长方形下方 */
left: 0;
width: 200px;
height: 100px; /* 半圆的直径 */
background-color: #4caf50; /* 半圆颜色 */
border-radius: 0 0 50% 50%; /* 仅设置下半部分为圆角 */
}
示例 3:使用 ::after
添加标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fix Clip Path</title>
<style>
.btwrapper{
position: relative; /* 为子元素提供定位参考 */
width: 60px;
height: 100px;
}
.svg-shape {
position: absolute; /* 定位矩形到父容器 */
top: 0; /* 放置在主矩形的下方 */
left:50%;
width: 60px;
height: 100px;
background-color: black;
clip-path: path('M25 1 7 1A6 6 90 001 7L1 51A6 6 90 007 57H19A6 6 90 0125 62Z');
}
.rectangle-below {
position: absolute; /* 定位矩形到父容器 */
top: 0%; /* 放置在主矩形的下方 */
right: 0;
width: 5px;
height: 100vh;
background-color: #4caf50; /* 绿色背景 */
}
</style>
</head>
<body>
<div class="btwrapper">
<!-- 主圆角矩形 -->
<div class="svg-shape"></div>
<!-- 下方的独立矩形 -->
<div class="rectangle-below"></div>
</div>
</body>
</html>
其他伪元素
除了 ::after
,还有其他常见的伪元素,例如:
::before
:插入到元素内容之前。::placeholder
:样式化表单元素的占位符文本。::selection
:改变用户选中内容的样式。