Table of Contents
What are::before and ::after?
Application of::before and ::after
给标题加括号
给标题加引号
不设置quotes
标题
Home Web Front-end CSS Tutorial Detailed explanation of pseudo-elements in CSS::before and ::after

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

Sep 14, 2021 am 10:14 AM
::after ::before css Pseudo 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>
Copy after login

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>
Copy after login

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

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

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

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>
Copy after login

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;
}复制代码
Copy after login

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>
Copy after login

Add quotation marks

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

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

Not specified, default

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

<h3 id="不设置quotes">不设置quotes</h3>
Copy after login

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>
Copy after login

The layout is done by placing <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>
Copy after login

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>
Copy after login

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);
}
Copy after login

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

1)具有简单文本的元素。它会被取代。
2)一个包含<img src="/static/imghw/default1.png" data-src="img/cat.jpg" class="lazy" alt="Detailed explanation of pseudo-elements in CSS::before and ::after" >在其中的元素。它也会被取代。
3)<img src="/static/imghw/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;
}
Copy after login

方式二:

.modern-clearfix {
    display: flow-root;
}
Copy after login

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 id="page-wrap">
    <img  src="/static/imghw/default1.png"  data-src="img/cat.jpg"  class="lazy"   id="logo" alt="Detailed explanation of pseudo-elements in CSS::before and ::after" >
    <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>
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The Roles of HTML, CSS, and JavaScript: Core Responsibilities The Roles of HTML, CSS, and JavaScript: Core Responsibilities Apr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

How to write split lines on bootstrap How to write split lines on bootstrap Apr 07, 2025 pm 03:12 PM

There are two ways to create a Bootstrap split line: using the tag, which creates a horizontal split line. Use the CSS border property to create custom style split lines.

Understanding HTML, CSS, and JavaScript: A Beginner's Guide Understanding HTML, CSS, and JavaScript: A Beginner's Guide Apr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

How to set up the framework for bootstrap How to set up the framework for bootstrap Apr 07, 2025 pm 03:27 PM

To set up the Bootstrap framework, you need to follow these steps: 1. Reference the Bootstrap file via CDN; 2. Download and host the file on your own server; 3. Include the Bootstrap file in HTML; 4. Compile Sass/Less as needed; 5. Import a custom file (optional). Once setup is complete, you can use Bootstrap's grid systems, components, and styles to create responsive websites and applications.

How to insert pictures on bootstrap How to insert pictures on bootstrap Apr 07, 2025 pm 03:30 PM

There are several ways to insert images in Bootstrap: insert images directly, using the HTML img tag. With the Bootstrap image component, you can provide responsive images and more styles. Set the image size, use the img-fluid class to make the image adaptable. Set the border, using the img-bordered class. Set the rounded corners and use the img-rounded class. Set the shadow, use the shadow class. Resize and position the image, using CSS style. Using the background image, use the background-image CSS property.

How to resize bootstrap How to resize bootstrap Apr 07, 2025 pm 03:18 PM

To adjust the size of elements in Bootstrap, you can use the dimension class, which includes: adjusting width: .col-, .w-, .mw-adjust height: .h-, .min-h-, .max-h-

How to use bootstrap button How to use bootstrap button Apr 07, 2025 pm 03:09 PM

How to use the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text

See all articles