伪元素
伪元素 用于在元素的内容前后或特定部分插入虚拟元素,并为其添加样式,无需修改 HTML 结构。
语法:使用双冒号 ::
(现代规范)
以下是一些常见的CSS伪元素的示例:
1.::before
: 在元素内容的前插入虚拟元素。
2.::after
: 在元素内容的后插入虚拟元素。
3.::first-line
: 选择元素的第一行文本。
4.::first-letter
: 选择元素的首字母。
5. ::selection
: 设置用户选中文本的样式
6.::placeholder
: 设置输入框占位符文本的样式
伪元素的一些简单示例:
清除浮动
.clearfix::after {content: "";display: block;clear: both;
}
自定义列表符号
ul li::before {content: "•";color: red;margin-right: 8px;
}
伪元素在HTML页面使用实例:
<!DOCTYPE html>
<html>
<head><title>CSS伪元素示例</title><style>/* 在元素的内容前插入新内容并设置样式 */h1::before {content: "-> "; color: blue;}/* 在元素的内容后插入新内容并设置样式 */p::after {content: " (end)";color: red;}/* 选择元素的第一行文本并设置样式 */p::first-line {color: green;font-weight: bold;}/* 选择元素的第一个字母并设置样式 */p::first-letter {font-size: 24px;color: orange;}</style>
</head>
<body><h1>Title</h1><p>This is a paragraph of text. </p>
</body>
</html>