Using CSS Pseudo Elements :before And :after

Posted January 21, 2013 at 9:38 AM by Ben Nadel

Tags: HTML / CSS

The CSS pseudo elements, :before and :after, have been around since IE8. So, this is probably not news to many of you. But, for me personally, I just started using the :before and :after pseudo elements and I've been absolutely loving them! They making it much easier to keep design-centric elements out of your markup and in your CSS (where they belong). Anyway, I thought I'd put together a quick demo in case anyone else is late to the party.


 
 
 

 
  
 
 
 

The CSS pseudo elements, :before and :after, prepend and append content to the selected elements, respectively. By default, these elements have an "inline" display quality; but, their display property can be set using CSS just as with any other element. In order for :before and :after pseudo elements to work, they must have a "content" property. This property can be a string value:

  • div:after {
  • content: "Hello World" ;
  • }

... or it can be a URL to an image:

  • div:after {
  • content: url( "img/icon.png" ) ;
  • }

If you don't want to render any content, you can use the empty string; but, you must supply the "content" property in all cases.

These pseudo elements don't show up in the DOM. But, if you're using Firebug or Chrome Dev Tools, you can still view and tweak the pseudo element CSS in the style inspector. These pseudo elements can be styled in the exact same way that any other element can be styled. It's pretty awesome.

That said, here's a quick demo of the :before and :after pseudo elements in action:

  • <!doctype>
  • <html>
  • <head>
  • <meta charset="utf-8" />
  •  
  • <title>CSS Pseudo Elements :before And :after</title>
  •  
  • <style type="text/css">
  •  
  • a.button {
  • background-color: #F0F0F0 ;
  • border: 1px solid #CCCCCC ;
  • border-radius: 4px 4px 4px 4px ;
  • color: #333333 ;
  • display: block ;
  • font-size: 30px ;
  • padding: 6px 30px 4px 58px ;
  • position: relative ;
  • text-decoration: none ;
  • width: 100px ;
  • }
  •  
  • a.button:before {
  • background-color: #FF0066 ;
  • border-radius: 3px 3px 3px 3px ;
  • color: #FFFFFF ;
  • content: "NEW" ;
  • font-family: sans-serif ;
  • font-size: 15px ;
  • left: 9px ;
  • line-height: 15px ;
  • margin-top: -10px ;
  • padding: 3px 3px 2px 3px ;
  • position: absolute ;
  • text-align: center ;
  • top: 50% ;
  • }
  •  
  • a.button:after {
  • background-color: #FFFFFF ;
  • border: 1px solid #DADADA ;
  • border-radius: 22px 22px 22px 22px ;
  • color: #333333 ;
  • content: "\00BB" ;
  • display: none ;
  • font-size: 30px ;
  • height: 28px ;
  • line-height: 26px ;
  • margin-top: -14px ;
  • position: absolute ;
  • right: 6px ;
  • text-align: center ;
  • text-indent: 1px ;
  • top: 50% ;
  • width: 28px ;
  • }
  •  
  • a.button:hover:after {
  • display: block ;
  • }
  •  
  • </style>
  • </head>
  • <body>
  •  
  • <h1>
  • CSS Pseudo Elements :before And :after
  • </h1>
  •  
  • <a href="#" class="button">
  • Button
  • </a>
  •  
  • </body>
  • </html>

According to the HTML markup, there's nothing but a button with the text, "Button." However, when you render the page, you can see the "NEW" tag:


 
 
 

 
 CSS pseudo elements, :before and :after. 
 
 
 

This "NEW" tag was supplied by the :before pseudo element. But, our CSS also has an :after pseudo element with an initial display of, "none;" This pseudo element is set to only show on :hover:


 
 
 

 
 CSS pseudo elements, :before and :after. 
 
 
 

Support for these CSS pseudo elements is IE8+, and basically every other browser. But, the nice thing about the pseudo elements is that they are intended primarily for design elements. This means that you can still gracefully degrade in IE<=7 using the same HTML and CSS. And, like I said, I've only just started using them in my current project; but, so far, they've made life so much easier!




Reader Comments

Jan 21, 2013 at 9:47 AM // reply »
9 Comments

Lovely, aren't they? ;)


Jan 21, 2013 at 9:50 AM // reply »
11,246 Comments

@All,

FYI, here's one of the many places you can look up the hex-encoding for special HTML characters like &raquo; -> \00BB:

http://www.yellowpipe.com/yis/tools/ASCII-HTML-Characters/index.php


Jan 21, 2013 at 9:50 AM // reply »
11,246 Comments

@Gary,

Werd up!


Jan 21, 2013 at 10:15 AM // reply »
272 Comments

@Ben,

You know those websites that mark mandatory form fields with asterisk on the label? :before or :after is usually how they do it (hopefully with redundant styling for graceful degradation):

  • label.mand {/* font-weight:bold or whatever */}
  • label.mand:after {content: " *"}

Cool before it was cool, huh.


Jan 21, 2013 at 10:34 AM // reply »
11,246 Comments

@WebManWalking,

It's funny you mention that - when I was looking into the pseudo elements, the mandatory-field was one of the first examples I found.


Jan 21, 2013 at 10:50 AM // reply »
272 Comments

@Ben,

Speaking of CSS and mandatory fields, y'know what I wish you could say? :for(subselector). Example:

  • label:for(input[required],select[required],textarea[required]) {font-weight:bold}
  • label:for(input[required],select[required],textarea[required]):after {content: " *"}

Then all you'd have to do is add required. No parallel editing. Forms are such a big part of web development, it would be worth it, even if only label ever used it.

**sigh**


Jan 21, 2013 at 10:56 AM // reply »
11,246 Comments

@WebManWalking,

That would be cool. I think there is a :has() selector (or maybe that's only in jQuery). But, that requires a descendant relationship, which would probably not be true for a "label" element.


Jan 21, 2013 at 11:50 AM // reply »
9 Comments

Actually, though I'm guilty of doing it myself, I don't think using :before to add an asterisk to a required field is good usability. A screen reader won't be able to pick that asterisk up - unless they've changed recently to pick up CSS 'content' values.

Still, they're a great way to add design to markup without the quality of the code suffering. I like to add them as block elements with absolute positioning to get an image from my spriteset to appear behind or next to a link... or any number of similar implementations.

They're also great for adding text content that is useful only to visual users.


Jan 22, 2013 at 7:47 AM // reply »
1 Comments

@Ben - great post! I've been using pseudo selectors more frequently since IE6/7 usage has been falling among clients and they are indeed and massive time-saver and also a much more elegant way to add this kind of design feature.

@Gary - many screen readers are now adopting WAI-ARIA features so you could substitute the hard-coded asterisk for

  • aria-required="true"

on the form element itself. Even though the asterisk is a well-known convention, I prefer the use of attributes to denote this sort of thing, particularly when there's the risk of the label not being linked to that field via its "for" attribute.


Jan 23, 2013 at 8:09 PM // reply »
272 Comments

@Ben,

You know what's even more appealing about :for(subselector)? It fits some of the things they're doing in CSS4 selectors:

http://coding.smashingmagazine.com/2013/01/21/sneak-peek-future-selectors-level-4/

Checkout :matches(). It takes a subselector as its argument! So you just KNOW they would be warm to the syntax. If only I knew how to submit a new feature request!


Jan 24, 2013 at 12:28 AM // reply »
11,246 Comments

@Gary,

Yeah, I've been loving them for inserting icons (using sprites) without having to put in an extra (and empty) span/i/b tab in the markup.


Jan 24, 2013 at 12:30 AM // reply »
11,246 Comments

@WebManWalking,

Uggg, I'm still catching up on CSS3 :D


Jan 26, 2013 at 4:26 AM // reply »
63 Comments

Ben ...

Charmap.exe has the unicode tables for ya' without the browser ;-)

start -> run -> charmap.exe


Jan 28, 2013 at 9:42 PM // reply »
11,246 Comments

@Edward,

I just did a bit of Googling and it looks like CMD+Option+T brings up the Character Input thing for Mac OSX. I just did it, and it's not the easiest thing to use. But, for example, I just copied the "Much Greater Than" to my clipboard. Pasted:

?
MUCH GREATER-THAN
Unicode: U+226B, UTF-8: E2 89 AB

Interesting...


Jan 28, 2013 at 9:43 PM // reply »
11,246 Comments

@Edward,

... and you can see that my blog doesn't have UTF-8 support :/


Jan 28, 2013 at 10:19 PM // reply »
63 Comments

On Nix you have WAY more support for char conversion ...

$ man iconv ...

done. :-)


Feb 14, 2013 at 5:24 PM // reply »
1 Comments

Very usueful tutorial. I've always wanted to learn more about these pseudo-elements. I guess this is the right moment.



Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
May 25, 2013 at 10:08 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
@Ben, my question is that i want the current node with its tag and its parent node. i just want only that data. So, give me the solution for that. and remember solution is working on " xpath 1.0 ... read »
May 25, 2013 at 10:01 AM
Using "//" And ".//" Expressions In XPath XML Search Directives In ColdFusion
hey ben, i want get my current node tag and also want the root node tag withing. So, how can i fix it.. ! ... read »
May 24, 2013 at 5:39 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Adam Oops! My mistake! I hadn't gotten that far in my testing - I'm still baby stepping my way through the process. ... read »
May 24, 2013 at 5:13 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
Hi Jason, Thanks for checking up on that, but I still stand firm on my position. :) There are actually two listLast()'s in use, and you're right that the one using a space as a delimiter is fine. ... read »
May 24, 2013 at 4:45 PM
Ask Ben: Manually Enforcing Basic HTTP Authorization In ColdFusion
@Ben I have been lurking your site for quite some time, and haven't stepped up to comment until today. Thanks for all the great info - keep it up! @Adam I believe you are mistaken... as the commen ... read »
May 24, 2013 at 11:21 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@WebManWalking, Ha ha, let's us never speak of justifying "##" notation again :P ... read »
May 24, 2013 at 11:18 AM
Strange Interaction Between DeserializeJson(), ArrayContains(), And Database Values In ColdFusion
@Ben, Ah, so it was indeed how I vaguely remembered it to be: A direct assignment value = users.id[ i ] causes value to retain the sticky datatype of the query column. Although unnecessary in ... read »
May 24, 2013 at 9:11 AM
Preventing Links In Standalone iPhone Applications From Opening In Mobile Safari
@Brandon, Hi, No, I haven't been able to do that. I have just kept it as it is. ... read »
InVision App - Prototyping Made Beautiful With Prototyping Tools