深入了解::before 和 ::after 伪元素

article/2025/11/3 15:15:29

点击上方 前端瓶子君,关注公众号

回复算法,加入前端编程面试算法每日一题群

本文从最简单的开始,解释如何理解和使用::before和::after。然后再在实际使用场景中去应用它。

::before和::after是什么?

::before和::after可以添加到选择器以创建伪元素的关键字。伪元素被插入到与选择器匹配的元素内容之前或之后。

1.png

content属性

1)::before和::after下特有的content,用于在css渲染中向元素逻辑上的头部或尾部添加内容。

2)::before和::after必须配合content属性来使用,content用来定义插入的内容,content必须有值,至少是空

3)这些添加不会出现在DOM中,不会改变文档内容,不可复制,仅仅是在css渲染层加入。所以不要用:before或:after展示有实际意义的内容,尽量使用它们显示修饰性内容

content可取以下值:

string

使用引号包一段字符串,将会向元素内容中添加字符串

a.png
 p::before{content: "《";color: #000000;
}
p::after{content: "》";color:#000000;
}<p>JavaScript高级程序设计</p>复制代码

attr()

通过attr()调用当前元素的属性,比如将图片alt提示文字或者链接的href地址显示出来。

a::after {content: ' → ' attr(href); /* 在 href 前显示一个箭头 */
}<a href="https://www.baidu.com/">百度地址</a>
复制代码
b.png
 a::after{content: "【" attr(href) "】";
}<a href="https://www.baidu.com/">百度地址</a>
复制代码

url()/uri()

用于引用媒体文件。比如:“百度”前面给出一张图片,后面给出href属性。

a::before{content: url("img/baidu_jgylogo3.gif");
}
a::after{content:"("attr(href)")";
}<a href="https://www.baidu.com/">百度地址</a>
复制代码

注意

1)URL不能使用引号。如果你将URL用引号括起来,那么它会变成一个字符串和插入文本“url(image.jpg)”作为其内容,插入的而不是图像本身。

2)content属性,直接使用图片,即使写width,height也无法改变图片大小;

解决方案:如果要解决这个问题,可以把content:''写成空,使用background:url()来添加图片

/*伪元素添加图片:*/
.wrap:after{/*内容置为空*/content:"";/*设置背景图,并拉伸*/background:url("img/06.png") no-repeat center;/*必须设置此伪元素display*/display:inline-block;/*必须设置此伪元素大小(不会被图片撑开)*/background-size:100%;width:100px;height:100px;
}
复制代码

3)苹果端伪元素不生效,img、input和其他的单标签是没有:after和:before伪元素的(在部分浏览器中没有,如:苹果端会发现无效),因为单标签本身不能有子元素。

解决方案:给img包一个div可以解决

4)想要动态改变伪元素的图片,可以给当前元素添加伪元素图片的基础样式,再动态class来写伪元素的图片。

::before和::after的应用

配合quotes 属性使用

加括号

 h1{quotes:"(" ")";  /*利用元素的quotes属性指定文字符号*/
}
h1::before{content:open-quote;
}
h1::after{content:close-quote;
}<h1>给标题加括号</h1>
复制代码

加引号

 h2{quotes:"\"" "\"";  /*添加双引号要转义*/
}
h2::before{content:open-quote;
}
h2::after{content:close-quote;
}<h2>给标题加引号</h2>
复制代码

不指定,默认

 h3::before{content:open-quote;
}
h3::after{content:close-quote;
}<h3>不设置quotes</h3>
复制代码

装饰标题

2.png
h1 {display: grid;grid-template-columns: minmax(50px, 1fr) auto minmax(50px, 1fr);align-items: center;text-align: center;gap: 40px;
}h1::before, h1::after {content: '';border-top: 6px double;
}<h1>标题</h1>
复制代码

布局是通过将<h1>元素变成 3 列来实现的。左列和右列是双线,宽度均为minmax(50px, 1fr),这意味着它们的匹配宽度始终不小于50px。标题文本整齐地居中居中。

彩带标题

3.png
 h1 {position: relative;margin: 0 auto 20px;padding: 10px 40px;text-align: center;background-color: #875e46;
}h1::before, h1::after {content: '';width: 80px;height: 100%;background-color: #724b34;/* 定位彩带两端形状的位置,并且放在最底层 */position: absolute;z-index: -1;top: 20px;/* 彩带两端的形状 */clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%, 25% 50%);/* 绘制并定位彩带的阴影三角形 */background-image: linear-gradient(45deg, transparent 50%, #5d3922 50%);background-size: 20px 20px;background-repeat: no-repeat;background-position: bottom right;
}h1::before {left: -60px;
}h1::after {right: -60px;transform: scaleX(-1); /* 水平翻转 */
}
---------------------------<h1>标题</h1>
复制代码

实现更逼真的阴影

image.png
.box{margin:10px;width:300px;height:100px;border-radius:10px;background:#ccc}
.shadow{position:relative;max-width:270px;box-shadow:0 1px 4px rgba(0,0,0,.3),0 0 20px rgba(0,0,0,.1) inset}
.shadow::after,.shadow::before{position:absolute;z-index:-1;content:""}
.shadow::after,.shadow::before{position:absolute;bottom:15px;left:10px;z-index:-1;width:50%;height:20%;content:""}
.shadow::after,.shadow::before{position:absolute;bottom:15px;left:10px;z-index:-1;width:50%;height:20%;box-shadow:0 15px 10px rgba(0,0,0,.7);content:"";transform:rotate(-3deg)}
.shadow::after{right:10px;left:auto;transform:rotate(3deg)}<div class="box shadow"></div>
复制代码

替换内容

有些情况下content可以不使用::before或::after。如果content设置为单个图像,那么你可以直接在元素上使用它来替换该元素的 HTML 内容。

如页面上分别有以下三个内容:

5.png

加了replace类之后

.replace {content: url(img/replace.png);
}
复制代码
6.png

1)具有简单文本的元素。它会被取代。
2)一个包含<img>在其中的元素。它也会被取代。
3)<img>直接一个元素。Firefox不会取代它,但其他浏览器会。

清除浮动

方式一:

.classic-clearfix::after {content: '';display: block;clear: both;
}
复制代码

方式二:

.modern-clearfix {display: flow-root;
}
复制代码
7.png

模拟float:center的效果

float没有center这个取值,但是可以通过伪类来模拟实现。

原理:左右通过::before float各自留出一半图片的位置,再把图片绝对定位上去。

d.png
body { font: 14px/1.8 Georgia, serif;}
#page-wrap { width: 60%; margin: 40px auto; position: relative; }
#logo { position: absolute; top: 0; left: 50%; margin-left: -125px; }
#l, #r { width: 49%; }
#l { float: left; }
#r { float: right; }
#l:before, #r:before { content: ""; width: 125px; height: 250px; }
#l:before { float: right; }
#r:before { float: left; }<div id="page-wrap"><img src="img/cat.jpg" id="logo"><div id="l"><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p></div><div id="r"><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p></div>
</div>
复制代码
e.png

引用参考:

W3C官方文档[2]

Diving into the ::before and ::after Pseudo-Elements[3]

Faking ‘float: center’ with Pseudo Elements[4]


小可爱看完就点个赞再走吧!????????????

关于本文

来源:Axjy

https://juejin.cn/post/6986629782666477599

最后

欢迎关注【前端瓶子君】✿✿ヽ(°▽°)ノ✿

回复「算法」,加入前端编程源码算法群,每日一道面试题(工作日),第二天瓶子君都会很认真的解答哟!

回复「交流」,吹吹水、聊聊技术、吐吐槽!

回复「阅读」,每日刷刷高质量好文!

如果这篇文章对你有帮助,「在看」是最大的支持

 》》面试官也在看的算法资料《《

“在看和转发”就是最大的支持


http://chatgpt.dhexx.cn/article/MwJtiXme.shtml

相关文章

:after和:before的作用及使用方法

1. :before 和 :after 的主要作用是在元素内容前后加上指定内容&#xff0c;示例&#xff1a; HTML代码&#xff1a; <p>你好</p> CSS代码&#xff1a; p:before{content: Hello;color: red; } p:after{content: Tom;color: red; } 效果如图&#xff1a; 以上代码…

::before和::after伪元素的用法案例

CSS3中伪类采用单冒号写法&#xff0c;伪元素采用双冒号写法。 伪类举例——:hover,:link,:active,:target。 伪元素举例——::before,::after,::first-letter,::first-line,::selection。 一、介绍 今天写网页时遇到一个问题&#xff0c;视口的背景中插入一个小图标的话&a…

beforeSend 出现跨域问题,header里直接设置token就没问题----Day1

一开始前端调用后端接口出现跨域问题&#xff0c;右键查看元素&#xff0c;会有跨域错误提示&#xff0c;类似下图&#xff0c;后来找后端设置了一下&#xff0c;问题解决。可以登录获取token等参数了。 但是 请求设备列表时&#xff0c;beforeSend 中设置token却失败了&#x…

after和before的作用及使用方法

:after和:before的作用及使用方法 1、 :before 和 :after 的主要作用是在元素内容前后加上指定内容&#xff0c;示例&#xff1a; HTML代码&#xff1a; <p>你好</p>CSS代码&#xff1a; p:before{content: Hello;color: red; } p:after{content: Tom;color: r…

@Before, @BeforeClass, @BeforeEach 和 @BeforeAll之间的不同

1. 不同注解的区别如下&#xff1a; 特性 Junit 4Junit 5 在当前类的所有测试方法之前执行。注解在静态方法上。此方法可以包含一些初始化代码。BeforeClassBeforeAll 在当前类中的所有测试方法之后执行。注解在静态方法上。此方法可以包含一些清理代码。AfterClassAfterAll 在…

HTML中 :before 和 :after 的用法

1. :before 和 :after 的主要作用是在元素内容前后加上指定内容&#xff0c;示例&#xff1a; <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEed…

:before和:after的使用方法

伪元素可以让我们很方便的加入一个样式&#xff0c;比如在字体前加一个icon&#xff0c;或者加一个下换线&#xff0c;可以不占一个元素的位置&#xff0c;使用起来也很方便&#xff0c;现在介绍一下使用的方法。 注意&#xff1a;:before和:after中的content是必加项 <!DO…

@Before和@After的区别

通常我们使用JUnit的时候&#xff0c;会有一些方法需要提前或最后执行&#xff0c;则需要如下几种方式进行注解

css中::before ::after的用法

一、介绍 ::before和::after是伪元素&#xff0c;&#xff08;css3中为了与伪类做区别&#xff0c;伪元素采用双冒号的写法&#xff1b;但因为兼容性的问题&#xff0c;所以现在大部分还是统一的单冒号&#xff0c;比如:first-line、:first-letter、:before、:after等&#xf…

:before、:after伪元素的用法 !

:after 伪元素在元素之后添加内容。:before伪元素在元素之前添加内容。 这个伪元素允许创作人员在元素内容的最后面插入生成内容。默认地&#xff0c;这个伪元素是行内元素&#xff0c;不过可以使用属性 dispiay 改变这一点。 &#xff1a;before和&#xff1a;&#xff1a;be…

CSS中的:before和 :after

1. &#xff1a;before和 &#xff1a;after CSS中的:befor、:after都会创建一个伪元素&#xff0c;其中:befor创建的伪元素是所选元素的第一个子元素&#xff0c;:after创建的伪元素是所选元素的最后一个子元素。 :befor、:after创建的伪元素**默认样式为内联样式**。 &…

::before和::after伪元素的用法

一、介绍 css3为了区分伪类和伪元素&#xff0c;伪元素采用双冒号写法。 常见伪类——:hover,:link,:active,:target,:not(),:focus。 常见伪元素——::first-letter,::first-line,::before,::after,::selection。 ::before和::after下特有的content&#xff0c;用于在css渲…

after::和before::的用法

:after和:before的作用及使用方法 1. :before 和 :after 的主要作用是在元素内容前后加上指定内容&#xff0c;示例&#xff1a; HTML代码&#xff1a; <p>你好</p> CSS代码&#xff1a; p:before{content: Hello;color: red; } p:after{content: Tom;color: red;…

before 和after的用法

转载自&#xff1a;lur88 一、介绍 css3为了区分伪类和伪元素&#xff0c;伪元素采用双冒号写法。(:before和:after是在CSS2中提出来的&#xff0c;CSS3中的写法是::before和::after) 常见伪类——:hover,:link,:active,:target,:not(),:focus。 常见伪元素——::first-letter,…

before和after的用法

一、介绍 css3为了区分伪类和伪元素&#xff0c;伪元素采用双冒号写法。(:before和:after是在CSS2中提出来的&#xff0c;CSS3中的写法是::before和::after) 常见伪类——:hover,:link,:active,:target,:not(),:focus。 常见伪元素——::first-letter,::first-line,::before…

css中的before与after

before与after是css中的两个伪元素。所谓的伪元素就是一个虚假的元素&#xff0c;并插入到目标元素内容的之前与之后&#xff0c;我们一般可以通过css来控制它。其实before与after的编码是非常的简单的&#xff0c;就像我们在css中对他进行操作&#xff0c;比如设置他的背景颜色…

jquery中beforeSend和complete的使用 --- 提高用户体验设置请求头

beforeSend方法的用户主要有下面几个&#xff1a; 第一&#xff1a;用于在发送ajax请求之前设置请求头 即作为前端&#xff0c;如果我们希望在发送数据之前设置请求头&#xff0c;就可以像下面这么做&#xff1a; beforeSend: function(request) {request.setRequestHeader(&…

list对象转map stream /去重( 根据属性转Map或者分组)

根据某属性转换成Map &#xff0c; List<Student>转成Map<String, Student> 由List<Student>转成以Student的id当成Key&#xff0c;而Student当成Value的Map操作&#xff0c;即Map<String, Student>形式 List<Student> list new ArrayList<…

stream对象转map

方法1 直接指定key-value 方法2 按某字段分组

java常用的对象转map的几种方式

创建对象User package com.xqc;import java.util.Date;public class User {/**** ID*/private Integer id;/**** 用户名*/private String userName;/**** 岗位ID*/private Long jobId;/*** 生日*/private Date birthday;/**** 薪水*/private Double salary;public Integer get…