Definition and Usage
::before creates a pseudo-element that is the first child of the element matched. Often used to add cosmetic content to an element, by using the content property. This element is inline by default.
Syntax
element:before { style properties } /* CSS2 obsolete syntax (only needed to support outdated browsers) */ element::before { style properties } /* CSS3 syntax */
The ::before notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :before introduced in CSS 2.
Examples
Adding quotation marks
One simple example of using psuedo-elements is to provide quotation marks. Here we use both ::before and ::before to insert quotation characters.CSSq::before { content: "»"; color: blue; } q::after { content: '«'; color: red; }HTML
<q>Some quotes</q>, he said, <q>are better than none</q>.
To-do list
In this example we will create a simple todo list using psuedo-elements. This method can often be used to add small touches to the UI and improve user experience.JavaScriptvar list = document.querySelector('ul'); list.addEventListener('click', function(ev) { if( ev.target.tagName === 'LI') { ev.target.classList.toggle('done'); } }, false);HTML
<ul> <li>Buy milk</li> <li>Take the dog for a walk</li> <li>Exercise</li> <li>Write code</li> <li>Play music</li> <li>Relax</li> </ul>CSS
li { list-style-type: none; position: relative; margin: 1px; padding: 0.5em 0.5em 0.5em 2em; background: grey; } li.done { background: #CCFF99; } li.done::before { content: ''; position: absolute; border-color: #009933; border-style: solid; border-width: 0 0.3em 0.25em 0; height: 1em; top: 1.3em; left: 0.6em; margin-top: -1em; transform: rotate(45deg); width: 0.5em; }
Compatibility
Desktop browsers
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari (WebKit) |
---|---|---|---|---|---|
:before support | (Yes) | 1.0 (1.7 or earlier) | 8.0 | 4 | 4.0 |
::before support | (Yes) | 1.5 | 9.0 | 7 | 4.0 |
Support of animations and transitions | 26 | 4.0 (2.0) | Not supported | Not supported | Not supported |
Mobile browsers
Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|
:before support | NA | NA | NA | NA | NA |
::before support | NA | NA | NA | NA | 5.1 |
Support of animations and transitions | 26 | 4.0 (4.0) | Not supported | Not supported | Not supported |