search
HomeWeb Front-endCSS TutorialDetailed explanation of pseudo-elements in CSS::before and ::after
Detailed explanation of pseudo-elements in CSS::before and ::afterSep 14, 2021 am 10:14 AM
::after::beforecssPseudo element

This article will take you through the ::before and ::after pseudo-elements in CSS and see their applications. I hope it will be helpful to you!

Detailed explanation of pseudo-elements in CSS::before and ::after

This article starts from the simplest and explains how to understand and use ::before and ::after. Then apply it in actual usage scenarios.

What are::before and ::after?

::before and ::after are keywords that can be added to selectors to create pseudo-elements. Pseudo-elements are inserted before or after the content of the element matching the selector.

Detailed explanation of pseudo-elements in CSS::before and ::after

content attribute

1) For unique content under ::before and ::after, use Used to add content to the logical head or tail of an element in CSS rendering.

2) ::before and ::after must be used with the content attribute. content is used to define the inserted content. content must have a value, at least empty

3) These additions will not Appearing in the DOM will not change the document content and cannot be copied. It is just added in the CSS rendering layer. So don’t use :before or :after to display meaningful content, try to use them to display decorative content

content can take the following values:

string

Using quotation marks to wrap a string will add the string to the element content

Detailed explanation of pseudo-elements in CSS::before and ::after

 p::before{
    content: "《";
    color: #000000;
}
p::after{
    content: "》";
    color:#000000;
}

<p>JavaScript高级程序设计</p>

attr()

Pass attr() calls the attributes of the current element, such as displaying the image alt prompt text or the href address of the link.

Detailed explanation of pseudo-elements in CSS::before and ::after

a::after {
    content: &#39; → &#39; attr(href); /* 在 href 前显示一个箭头 */
}

 <a href="https://www.baidu.com/">百度地址</a>

Detailed explanation of pseudo-elements in CSS::before and ::after

 a::after{
    content: "【" attr(href) "】";
}

<a href="https://www.baidu.com/">百度地址</a>

url()/uri()

is used to reference media files . For example: "Baidu" gives a picture in the front and the href attribute in the back.

Detailed explanation of pseudo-elements in CSS::before and ::after

a::before{
    content: url("img/baidu_jgylogo3.gif");
}
a::after{
    content:"("attr(href)")";
}

<a href="https://www.baidu.com/">百度地址</a>

Note

1) URLs cannot use quotation marks. If you enclose the URL in quotes, then it becomes a string and inserts the text "url(image.jpg)" as its content, instead of the image itself.

2) Content attribute, use the image directly, even if you write width and height, you cannot change the image size;

Solution: If you want to solve this problem, you can change content:'' Write it as empty and use background:url() to add pictures

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

3) The pseudo-elements on the Apple side do not take effect. img, input and other single tags do not have :after and :before pseudo-elements ( It is not available in some browsers, for example, Apple will find it invalid) because a single tag itself cannot have child elements.

Solution: Wrapping the img with a div can solve the problem

4) If you want to dynamically change the image of the pseudo element, you can add the basic style of the pseudo element image to the current element. , and then use the dynamic class to write the picture of the pseudo element.

Application of::before and ::after

Use with quotes attribute

Detailed explanation of pseudo-elements in CSS::before and ::after

Add brackets

 h1{
    quotes:"(" ")";  /*利用元素的quotes属性指定文字符号*/
}
h1::before{
    content:open-quote;
}
h1::after{
    content:close-quote;
}

<h1 id="给标题加括号">给标题加括号</h1>

Add quotation marks

 h2{
    quotes:"\"" "\"";  /*添加双引号要转义*/
}
h2::before{
    content:open-quote;
}
h2::after{
    content:close-quote;
}

<h2 id="给标题加引号">给标题加引号</h2>

Not specified, default

 h3::before{
    content:open-quote;
}
h3::after{
    content:close-quote;
}

<h3 id="不设置quotes">不设置quotes</h3>

Decoration title

Detailed explanation of pseudo-elements in CSS::before and ::after

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: &#39;&#39;;
    border-top: 6px double;
}

<h1 id="标题">标题</h1>

The layout is done by placing <h1></h1>The element becomes 3 columns to achieve. The left column and the right column are double lines with a width of minmax(50px, 1fr), which means that their matching width is always no less than 50px. The title text is neatly centered.

Ribbon Title

Detailed explanation of pseudo-elements in CSS::before and ::after##

 h1 {
    position: relative;
    margin: 0 auto 20px;
    padding: 10px 40px;
    text-align: center;
    background-color: #875e46;
}

h1::before, h1::after {
    content: &#39;&#39;;
    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 id="标题">标题</h1>

Achieve more realistic shadows

Detailed explanation of pseudo-elements in CSS::before and ::after

.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>

Replacement content

In some cases content may not be used: :before or ::after. If content is set to a single image, then you can use it directly on an element to replace that element's HTML content.

For example, there are the following three contents on the page:

Detailed explanation of pseudo-elements in CSS::before and ::after

After adding the replace class

.replace {
    content: url(img/replace.png);
}

Detailed explanation of pseudo-elements in CSS::before and ::after

1)具有简单文本的元素。它会被取代。
2)一个包含<img src="/static/imghwm/default1.png" data-src="img/cat.jpg" class="lazy" alt="Detailed explanation of pseudo-elements in CSS::before and ::after" >在其中的元素。它也会被取代。
3)<img src="/static/imghwm/default1.png" data-src="img/cat.jpg" class="lazy" alt="Detailed explanation of pseudo-elements in CSS::before and ::after" >直接一个元素。Firefox不会取代它,但其他浏览器会。

清除浮动

方式一:

.classic-clearfix::after {
    content: &#39;&#39;;
    display: block;
    clear: both;
}

方式二:

.modern-clearfix {
    display: flow-root;
}

1Detailed explanation of pseudo-elements in CSS::before and ::after

模拟float:center的效果

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

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

1Detailed explanation of pseudo-elements in CSS::before and ::after

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>
    <img  src="/static/imghwm/default1.png" data-src="img/cat.jpg" class="lazy" alt="Detailed explanation of pseudo-elements in CSS::before and ::after" >
    <div>
        <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>
        <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>

1Detailed explanation of pseudo-elements in CSS::before and ::after

引用参考:

W3C官方文档

Diving into the ::before and ::after Pseudo-Elements

Faking ‘float: center’ with Pseudo Elements

原文地址:https://juejin.cn/post/6986629782666477599

作者:Axjy

相关推荐:《css视频教程》!

The above is the detailed content of Detailed explanation of pseudo-elements in CSS::before and ::after. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金--Axjy. If there is any infringement, please contact admin@php.cn delete
利用CSS怎么创建渐变色边框?5种方法分享利用CSS怎么创建渐变色边框?5种方法分享Oct 13, 2021 am 10:19 AM

利用CSS怎么创建渐变色边框?下面本篇文章给大家分享CSS实现渐变色边框的5种方法,希望对大家有所帮助!

css ul标签怎么去掉圆点css ul标签怎么去掉圆点Apr 25, 2022 pm 05:55 PM

在css中,可用list-style-type属性来去掉ul的圆点标记,语法为“ul{list-style-type:none}”;list-style-type属性可设置列表项标记的类型,当值为“none”可不定义标记,也可去除已有标记。

css与xml的区别是什么css与xml的区别是什么Apr 24, 2022 am 11:21 AM

区别是:css是层叠样式表单,是将样式信息与网页内容分离的一种标记语言,主要用来设计网页的样式,还可以对网页各元素进行格式化;xml是可扩展标记语言,是一种数据存储语言,用于使用简单的标记描述数据,将文档分成许多部件并对这些部件加以标识。

css3怎么实现鼠标隐藏效果css3怎么实现鼠标隐藏效果Apr 27, 2022 pm 05:20 PM

在css中,可以利用cursor属性实现鼠标隐藏效果,该属性用于定义鼠标指针放在一个元素边界范围内时所用的光标形状,当属性值设置为none时,就可以实现鼠标隐藏效果,语法为“元素{cursor:none}”。

rtl在css是什么意思rtl在css是什么意思Apr 24, 2022 am 11:07 AM

在css中,rtl是“right-to-left”的缩写,是从右往左的意思,指的是内联内容从右往左依次排布,是direction属性的一个属性值;该属性规定了文本的方向和书写方向,语法为“元素{direction:rtl}”。

css怎么实现英文小写转为大写css怎么实现英文小写转为大写Apr 25, 2022 pm 06:35 PM

转换方法:1、给英文元素添加“text-transform: uppercase;”样式,可将所有的英文字母都变成大写;2、给英文元素添加“text-transform:capitalize;”样式,可将英文文本中每个单词的首字母变为大写。

css怎么设置i不是斜体css怎么设置i不是斜体Apr 20, 2022 am 10:36 AM

在css中,可以利用“font-style”属性设置i元素不是斜体样式,该属性用于指定文本的字体样式,当属性值设置为“normal”时,会显示元素的标准字体样式,语法为“i元素{font-style:normal}”。

怎么设置rotate在css3的旋转中心点怎么设置rotate在css3的旋转中心点Apr 24, 2022 am 10:50 AM

在css3中,可以用“transform-origin”属性设置rotate的旋转中心点,该属性可更改转换元素的位置,第一个参数设置x轴的旋转位置,第二个参数设置y轴旋转位置,语法为“transform-origin:x轴位置 y轴位置”。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft