Detailed explanation of pseudo-elements in CSS::before and ::after
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!
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.
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
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.
a::after { content: ' → ' attr(href); /* 在 href 前显示一个箭头 */ } <a href="https://www.baidu.com/">百度地址</a>
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.
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
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
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 id="标题">标题</h1>
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
##
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 id="标题">标题</h1>
Achieve more realistic shadows
.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:.replace { content: url(img/replace.png); }
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: ''; display: block; clear: both; }
方式二:
.modern-clearfix { display: flow-root; }
模拟float:center的效果
float没有center这个取值,但是可以通过伪类来模拟实现。
原理:左右通过::before float各自留出一半图片的位置,再把图片绝对定位上去。
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>
引用参考:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

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.

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.

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

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.

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.

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 the Bootstrap button? Introduce Bootstrap CSS to create button elements and add Bootstrap button class to add button text
