preface
This article explains the content attribute, which is not frequently used in CSS. Through several practical cases, it takes you to master the usage of content from simple to deep, so as to make the code more concise and efficient.
definition
W3school is defined as follows:
The content attribute is used with the: before and: after pseudo elements to insert the generated content.
This attribute defines the generated content placed before or after the element. By default, this is often inline content, but the type of box created by this content can be controlled by the attribute display.
In the daily development of the front end, the content attribute is not used frequently, so developers generally do not have a deep understanding of it. They usually use it occasionally when clearing floating and font icons. Let's take a look at the wonderful use of content through various cases.
case
1. Clear float
<!--css--> .left .right .clear:after { content: ''; clear: both; display: block; } <!--html--> <div> <div>Left</div> <div>right</div> </div>
The two child elements. left and. right in the parent element. Container will be separated from the document flow after floating, and the container cannot be supported, resulting in the height of. Container being 0. Using the pseudo element: after to clear the float, three attributes are indispensable:
- content: ''; Add a pseudo element with empty content through: after.
- clear: both; Pseudo elements: after both sides of the floating clear.
- dispaly: block; Set block elements because clear is only valid for block elements.
When it comes to the clear attribute, the most used is clear: both, but left/right is rarely used, because both already contains the left/right feature, which is simple, direct and effective. To learn more about the clear attribute, you can take a look at Zhang Xinxu's great God Accurately understand the meaning and practical use of CSS clear:left/right.
2. Bubble window of small triangle
<!--css--> .box { width: 200px; height: 100px; border-radius: 5px; background: #fff; position: relative; } .box:after { content: ''; position: absolute; bottom: -20px; right: 20px; width: 0; height: 0; border-top: 10px solid #fff; border-bottom: 10px solid transparent; border-left: 10px solid transparent; border-right: 10px solid transparent; } <!--html--> <div></div>
effect:
With pseudo element: after, a bubble window with inverted triangular directivity in the lower right corner is realized. By adjusting the color and absolute positioning position of each edge of the border, you can draw bubble windows pointing to different points. It is realized with only one div tag. Is it simple and beautiful. You may think that this is a pseudo element: the effect of after has nothing to do with the content attribute. In fact, after does not take effect after removing the content.
3. Font Icon
The first is the special characters provided by the browser:
<!--css--> .music:before { content: '\266C'; color: red; } <!--html--> <span>a sunny day-Jay Chou</span>
effect:
The browser supports many font icons, such as weather ☀, snowflake ❄, Clover ☘, Tai Chi ☯ And other interesting characters. reference resources Comparison table of HTML special character coding of web pages.
The second is to introduce external font icons, such as Glyphicon Font Icon in Bootstrap:
<link rel="stylesheet" href="../static/css/bootstrap.min.css"> <!--html--> <span></span>
effect:
Why is there no CSS style here? Because the style of glyph heart has been defined in bootstrap.min.css, which is directly displayed in the Official website View on:
It should be noted that after bootstrap.min.css is introduced locally, the Font Icon Library glyphics-halfings-regular.wolf2 needs to be introduced to make the Font Icon effective.
<!--bootstrap.min.css--> <!--format Properties are used to help browsers recognize fonts--> @font-face { font-family: 'Glyphicons Halflings'; src: url(../fonts/glyphicons-halflings-regular.eot); src: url(../fonts/glyphicons-halflings-regular.eot?#iefix) format('embedded-opentype'), url(../fonts/glyphicons-halflings-regular.woff2) format('woff2'), url(../fonts/glyphicons-halflings-regular.woff) format('woff'), url(../fonts/glyphicons-halflings-regular.ttf) format('truetype'), url(../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular) format('svg') }
According to the above url path, put glyphs-halfings-regular.wolf2 into the following directory structure.
4. No content prompt
<!--css--> <!--:empty Space time matching--> div:empty:after { content: 'No data'; color: red; } <!--html--> <div>With content data</div> <div></div>
effect:
When the element content is empty, it is displayed through the content "no data temporarily". Usable scenario: after the background interface returns the data, it is inserted into the page DOM. When the background returned data is empty, it will directly prompt that there is no data through CSS, and JavaScript processing is not required.
An interesting phenomenon is that the content "no data temporarily" cannot be selected because pseudo elements are used to create elements that are not in the document tree. Although users can see these texts, they are not actually in the document tree.
5. Breadcrumb menu
<!--css--> ul li { display: inline-block; font-weight: bold; } ul li:not(:last-child):after { content: '\276D'; margin: 5px; } <!--html--> <ul> <li>home page</li> <li>commodity</li> <li>details</li> </ul>
effect:
This is another example where the content value is a special character, which completes the bread crumb menu with pseudo classes and pseudo elements.
6. Loading... Animation
<!--css--> .loading:after { content: "."; animation: loading 2s ease infinite; } @keyframes loading { 33% { content: ".."; } 66% { content: "..."; } } <!--html--> <p>Loading </p>
effect:
Meaning of animation value:
- Loading: animation name, which specifies that the name of the keyframe to be bound to the selector is loading.
- 2s: animation duration, which specifies the time to complete the animation for 2 seconds.
- ease: animation timing function, which specifies the speed curve of animation, first slow, middle fast and then slow.
- Infinite: animation iteration, which specifies that the number of times the animation should be played is infinite.
When 33% and 66% of the animation is completed, it is matched with the content to achieve the effect of dynamic "loading...".
7. Insert picture
<!--css--> .loading:before { content: url("../static/img/loading.gif"); vertical-align: middle; } <!--html--> <div> Loading... </div>
effect:
In addition to inserting font icons, content can also use the url() method to insert pictures. Similar to the background attribute, you can use the url to specify a picture path. The difference is that the content attribute cannot control the picture size and the use conditions are limited.
8. attr attribute content generation
<!--css--> .web:after { content: "("attr(href)")" } <!--html--> <a href="https://echeverra.cn">echevera</a>
effect:
The content value can also be the attr() method, which is used to obtain the value of the specified attribute and can be inserted into the specified location.
9. Half effect
<!--css--> span{ font-family: sans-serif; font-size: 30px; font-weight: bold; position: relative; color: green; } span:before{ content: attr(text); color: orange; position: absolute; left: 0; top: 0; width: 50%; overflow: hidden; } <!--html--> <span text="echeverra">echeverra</span> <span text="Bo">Bo</span> <span text="passenger">passenger</span>
effect:
The half side effect is to obtain the text attribute value through the attr() method. The attribute value is the same as its content. It cleverly sets the absolute positioning. It only displays half and covers the content of the original text. Is it cool to realize the half side effect of the text. It should be noted that some font family fonts have the problem that the text cannot overlap.
10. Text quotation marks
<!--css--> span { quotes: '"' '"'; } span:before { content: open-quote; } span:after { content: close-quote; } <!--html--> <p>Lu Xun said:<span>True warrior ,Dare to face the bleak life,Dare to face the dripping blood.</span></p>
effect:
Use the quotes attribute of the element to specify double quotation marks, use the open quote attribute value of content to set open quotation marks, and the close quote attribute value to set closed quotation marks. Of course, quotes can also specify other symbols.
11. Number of chapters added
<!--css--> ul{ counter-reset: section; } li{ list-style-type: none; counter-increment: section; } li:before{ content: counters(section, '-') '.'; } <!--html--> <ul> <li>Chapter I</li> <li>Chapter II <ul> <li>Chapter 21</li> <li>Chapter 22</li> <li>Chapter 23</li> </ul> </li> <li>Zhang jiesan</li> <li>Chapter IV</li> <li>Chapter V <ul> <li>Chapter 51</li> <li>Chapter 52</li> </ul> </li> <li>Chapter VI</li> </ul>
effect:
The counter counter method is used here, involving counter reset, counter increment, counter() and counters().
- Counter reset is used to specify the name of the counter. In the example, it is named section. At the same time, you can specify the starting count value of the counter, such as 1: counter reset: Section 1;, Do not specify. The default is 0.
- Counter increment is used to specify the value of each increment of the counter. For example, the counter increment is 2: counter increment: Section 2;, The default value is 1. As long as counter reset is specified, the value of the corresponding counter will change.
- counter(name, style) is used to output the value of the counter. Where name is the counter name, style is an optional parameter, and the default is Arabic numerals. You can also specify the values supported by list style type, such as Roman numeral lower Roman.
- counters(name, strings, style) is used to process nested counters. It is also the value of the output counter. Unlike counter(), there is an additional strings parameter, which represents the connection string of the sub sequence number. For example, the string of 1.1 is'., and 1-1 is' - '.
For a detailed tutorial on counters, you can also refer to Zhang Xinxu, the great God of CSS Detailed explanation of CSS counter counter (automatic increment of content directory serial number).
12. Calculate the number of checkbox es selected
<!--css--> form { counter-reset: count 0; } input[type="checkbox"]:checked { counter-increment: count 1; } .result:after { content: counter(count); } <!--html--> <form> <input type="checkbox" id="javaScript"> <label for="javaScript">javaScript</label> <input type="checkbox" id="PHP"> <label for="PHP">PHP</label> <input type="checkbox" id="Python"> <label for="Python">Python</label> <div>Selected:</div> </form>
effect:
Clever use of counter cooperation: checked pseudo class, select the counter to increase by 1, uncheck to decrease by 1, and use CSS to realize the dynamic counting function.
summary
Summary content attribute values can be as follows:
- String string, the most common, corresponding cases: clear floating, bubble window of small triangle, font icon, no content prompt, breadcrumb menu, loading... Animation.
- url() method, corresponding case: Insert picture.
- attr() method, corresponding cases: attr attribute content generation, half edge special effects.
- quotes quotation marks, corresponding to the case: text quotation marks.
- counter() method, counter function, corresponding case: add the number of chapters and calculate the number of checked boxes.
Although javaScript can also achieve most of the above functions and has higher flexibility, the advantage of using CSS is that it can greatly simplify development, do not occupy JS main threads and improve web performance.
In fact, the case of content is far more than this. While consulting relevant materials, I have also seen some other magical uses. Of course, the principle is roughly the same. The case of this article only takes you to understand the unknown side of content as much as possible, opens a new world and lets you draw inferences from one example. If it can be used in practical development, it will be Nice. I hope it can be helpful to you.
Have you learned "waste"?
The article started on my blog echeverra.cn/css-content , original article, reprint, please indicate the source.
Welcome to my WeChat official account. echeverra , learn and progress together! There will be resources and benefits from time to time!