preface

This article explains the content property in CSS, which is not frequently used. Through several practical cases, it takes you to master the usage of content from simple to profound, so that the code becomes more concise and efficient.

define

W3school is defined as follows:

The content attribute is used with :before and :after pseudo-elements to insert generated content.

This property is used to define the generated content placed before or after the element. By default, this tends to be inline content, but the type of box created by that content can be controlled with the display attribute.

The Content property is not used very often in daily front-end development, so developers generally don’t understand it very well and use it occasionally to clear floats and font ICONS. Here is a look at the clever use of content through various cases.

case

1. Clear floats

<! --css--> .left {float: left} .right {float: right} .clear:after { content: ''; clear: both; display: block; } <! <div class="left"> left </div> <div class="right"> right </div> </div>Copy the code

The parent element. Container’s two child elements. Left and. Right float out of the document flow and cannot support the container, resulting in a. Container height of 0. Use the pseudo-element :after to clear the float, all three attributes are required:

  • content: '';through:afterAdd a pseudo-element with empty content.
  • clear: both;Pseudo elements:afterBoth sides float clear.
  • dispaly: block;Set the block element becauseclearOnly valid for block elements.

When it comes to the clear attribute, the most commonly used is clear: both, left/right is rarely used, because both already contains the left/right feature, simple and direct also effective. Clear: Left/Right CSS Clear :left/ Right CSS Clear :left/ Right 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 class="box"></div>Copy the code

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 position of each border, you can draw the window pointing to different bubbles. It is simple and beautiful to use only a div tag. As you might expect, this is the effect of the pseudo-element :after, which has nothing to do with the content property. In fact, removing the content: After doesn’t work.

3. Font icon

The first is the browser’s own special characters:

<! --css--> .music:before { content: '\266C'; color: red; } <! <span class="music"> </span>Copy the code

Effect:

The browser supports many font ICONS such as: Weather ☀, Snowflake ❄, Shamrock ☘, Tai Chi ☯ and many more interesting characters. Refer to the HTML special character coding table.

The second is an externally introduced font icon, such as Glyphicon in Bootstrap:

<link rel="stylesheet" href=".. /static/css/bootstrap.min.css"> <! --html--> <span class="glyphicon glyphicon-heart"></span>Copy the code

Effect:

Bootstrap.min. CSS defines glyphicon-heart, which can be viewed directly on the website:

Note that after bootstrap.min. CSS is imported locally, the font icon library glyphicons-halflings-regular.woff2 needs to be imported for the font ICONS to take effect.

<! --bootstrap.min.css--> <! -- The format attribute is 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') }Copy the code

Place glyphicons-halflings-regular.woff2 in the following directory structure according to the above URL path.

4. No content prompt

<! --css--> <! --> div:empty:after {content: 'No data yet '; color: red; } <! </div> </div>Copy the code

Effect:

When the element content is empty, it is displayed through the content content “No data yet”. Available scenarios: After the background interface returns data, it inserts it into the DOM of the page. If the background interface returns empty data, the CSS displays a message indicating that no data is available. JavaScript is not required.

One interesting thing is that the content “no data yet” is not selected because pseudo-elements are used to create elements that are not actually in the document tree, even though the user can see the text.

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 > products < / li > < li > details < / li > < / ul >Copy the code

Effect:

Another example where the content value is a special character, with pseudo-classes and pseudo-elements to complete the breadcrumb menu.

6. Loading… animation

<! --css--> .loading:after { content: "."; animation: loading 2s ease infinite; } @keyframes loading { 33% { content: ".." ; } 66% { content: "..." ; }} <! -- HTML --> <p class="loading">Copy the code

Effect:

Animation meaning:

  • Loading: animation-name: specifies the keyframe name to be bound to the selector as loading.
  • 2s: animation-duration specifies the time it takes to complete the animation in 2 seconds.
  • Ease: animation-timing-function specifies the speed curve of the animation.
  • Infinite: animation-Iteration, which specifies that the animation should play an infinite number of times.

When 33% and 66% of the animation is completed, it can coordinate with the content to realize dynamic “loading…”. The effect.

7. Insert pictures

<! --css--> .loading:before { content: url(".. /static/img/loading.gif"); vertical-align: middle; } <! -- HTML --> <div class="loading"> </div>Copy the code

Effect:

In addition to inserting a font icon, content can also use the URL () method to insert an image, similar to background, which can specify an image path using the URL.

8. Attr attribute content generation

<! -- the CSS -- >. Web: after {content: "(" attr (href)") "} <! --html--> <a class="web" href="https://echeverra.cn">echevera</a>Copy the code

Effect:

The content value can also be the attr() method used to get the value of the specified property, which can be inserted at the specified location.

9. Side effects

 <!--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="博">博</span>
 <span text="客">客</span>
Copy the code

Effect:

The attr() method is used to obtain the value of the text attribute, which is the same as the content. It should be noted that some font-family characters cannot overlap.

10. Text quotes

<! -- CSS --> span {quotes: '"' "; } span:before { content: open-quote; } span:after { content: close-quote; } <! Lu Xun once said: < SPAN > True warriors, dare to face bleak life, dare to face dripping blood. </span></p>Copy the code

Effect:

Use the element’s quotes attribute to specify double quotes, the content’s open-quote attribute to set open quotes, and the close-quote attribute to set closed quotes. Other symbols can be specified, too.

11. Add chapters

<! --css--> ul{ counter-reset: section; } li{ list-style-type: none; counter-increment: section; } li:before{ content: counters(section, '-') '.'; } <! - HTML - > < ul > < li > chapter one < / li > < li > section 2 < ul > < li > chapter two a < / li > < li > chapter. < / li > < li > chapter 23 < / li > < / ul > < / li > < li > section 3 < / li > < li > section 4 < / li > < li > chapter five < ul > < li > section May 1 < / li > < li > 'section < / li > < / ul > < / li > < li > chapter six < / li > < / ul >Copy the code

Effect:

Here the counter counter method is used, involving the counter-reset, counter-increment, counter() and counters() attributes.

  • counter-resetUsed to specify the counter name, in this example namedsection, and you can specify the value at which the counter starts counting, such as 1:counter-reset: section 1;, do not specify the default is0.
  • counter-incrementUsed to specify the value by which the counter is incremented, for example, by 2:counter-increment: section 2;, the default value is 1,counter-incrementAs long as you specifycounter-reset, the corresponding counter value will change.
  • counter(name, style)Used to print the value of the counter. Among themnameIs the counter name,styleThis parameter is optional. The default value is an Arabic digit, or it can be specifiedlist-style-typeSupported values, such as Roman numeralslower-roman.
  • counters(name, strings, style)Used to handle nested counters, also output counter values, andcounter()The difference is there’s one morestringsParameter representing a connection string for a subserial number. For example,1.1thestringis'. '.1-1isThe '-'.

For a detailed tutorial on counters, you can also refer to CSS Counter counter (content directory serial number automatic increment) in detail.

12. Count the number of checkboxes

<! --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 class="result">Copy the code

Effect:

Ingenious use of counters with :checked pseudo class, selected counter increase 1, cancel selected minus 1, with CSS to achieve dynamic counting function.

conclusion

Summary Content attribute values can be the following:

  • String string, most common, corresponding cases: clear float, small triangle bubble window, font icon, no content prompt, breadcrumb menu, loading… The animation.
  • Url () method, corresponding case: Insert image.
  • Attr () method, corresponding cases: attR attribute content generation, half effect.
  • Quotes, corresponding case: text quotes.
  • Counter () method, counter function, corresponding case: add section number, calculate checkbox selected number.

While most of the above functions can be achieved using javaScript with greater flexibility, the advantage of using CSS is that it can greatly simplify development without tying up the MAIN JS thread and improving the performance of the Web.

In fact, the cases of Content are far more than that. While looking up relevant materials, I also saw some other magical uses. Of course, the principle is roughly the same. If it can be used in the actual development, it is more Nice, I hope to help you.

Did you learn to “waste”?


This article was originally published on my blog Echeverra.

Welcome to follow my wechat public number, learning and progress together! Uncertain when there are resources and welfare oh!