伪元素
今天讲的伪元素跟伪类定义是一样的,也是向某些选择器设置特殊的效果。但我觉得伪元素是用于将特殊的效果添加到某些选择器这种说法比较好一点。接下来重点来了,重点来了,伪元素和伪类是有很大区别滴。
它们之间最明显的区别就是伪类没有创造新的元素,而伪元素是创造了新的元素的。当然伪元素是一种逻辑上存在,但不会存在与文档树中的元素。即在html文件中发现不了它
所以伪元素作用主要是装饰内容 (无论是装饰图片还是音效) 而不需要更改HTML 的内容,从而帮助内容与样式更好地分离。
伪元素有哪些:
:first-letter 向文本的第一个字母添加特殊样式。
:first-line 向文本的首行添加特殊样式。
:before 在元素之前添加内容。
:after 在元素之后添加内容。
伪元素的使用:
1.清楚浮动
父级元素:after{
content:"";
height:0;
display:block;
clear:both;
}
2.实现序号
<h2></h2>
<style>
body {counter-reset:section;}
h2:before {
counter-increment: section;
content: "Chapter" counter(section) ".";
}
</style>
3.画图,如箭头,三角
箭头:
html:
<div class="triangle">
三角形
</div>
css:
```css
.triangle {
border: 1px solid;
width: 100px;
height: 100px;
margin-left: 100px;
position: relative;
}
.triangle::before{
content: "";
width: 30px;
height: 5px;
display: block;
background: red;
transform: rotate(45deg);
position: absolute;
}
.triangle::after {
content: "";
display: block;
width: 30px;
height: 5px;
display: block;
background: red;
transform: rotate(-45deg);
position: absolute;
}
三角:
html:
<div class="triangle">
三角形
</div>
css
.triangle::after {
content: "";
display: block;
/* width: 30px;
height: 5px;
display: block;
background: red;
transform: rotate(-45deg);
position: absolute;
top: -10px; */
width: 10px;
height: 0px;
border-top: 10px solid ;
border-bottom: 10px solid transparent;
border-right: 10px solid black;
position: absolute;
left: -20px;
top: 30px;
}