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

青灯夜游
Release: 2021-09-14 10:14:40
forward
2363 people have browsed it

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>给标题加括号</h1>
Copy after login

Add quotation marks

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

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

Not specified, default

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

<h3>不设置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>标题</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>标题</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 alt="Detailed explanation of pseudo-elements in CSS::before and ::after" >在其中的元素。它也会被取代。
3)<img 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="img/cat.jpg" 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!

Related labels:
source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!