Search notes:

CSS: content property

Add text before and/or after an element

The content property allows to add text before and/or after an element using the pseudo selectors ::before and ::after:
In the following example, text is prepended or appendd to an elements text depending on its classes:
<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>CSS property content on ::before and ::after pseudo elements</title>

  <style type="text/css">

     div              {color  : blue       }

     .odd::before     {content: "Odd: "    }
     .even::before    {content: "Even: "   }

     .prime::after    {content: " (prime)" }

  </style>

</head>
<body>

   <div                   >Some numbers:</div>
   <div class='odd'       >One          </div>
   <div class='even prime'>two          </div>
   <div class='odd  prime'>three        </div>
   <div class='even'      >four         </div>
   <div class='odd  prime'>five         </div>

</body>
</html>
Github repository about-css, path: /properties/content/before-after.html

Add more dynamic text with attr()

When using content, the attr(xyz) directive allows to insert the value of the matched element's attribute xyz.
In the following example, the divs with the num class have an attribute data-translation which is used in the content property to insert the translation after an element.
The example also demonstrates that it is possible to concatenate text: the translation is embedded in parentheses:
<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>content using attr()</title>
  <style type="text/css">

    .num::after {content: " (" attr(data-translation) ")"; }

  </style>
</head>
<body>


  <div class='num' data-translation="eins">one  </div>
  <div class='num' data-translation="zwei">two  </div>
  <div class='num' data-translation="drei">three</div>

</body>
</html>
Github repository about-css, path: /properties/content/attr.html

See also

When using non-ASCII characters, consider using the @charset CSS at-rule.
CSS properties

Index