What happens if several classes of the same element define: before a pseudo-element?

I use :before to bind links to user profiles with a symbol to indicate a user, examples include "administrator", "inactive user", "newbie", etc.

The fact is that it is possible to use more than one.

So what happens if more than one class in the link defines a :before pseudo-element with content ? Does the first concrete selector determine the first? Or do they both look alright? Whatever happens is this reliable behavior?

+5
css css-selectors pseudo-element
Jan 01 '13 at 15:39
source share
1 answer

The most specific selector takes precedence. This is mentioned in CSS2.1 :

Pseudo-elements behave like real elements in CSS with the exceptions described below, and elsewhere.

In terms of the actual behavior of the browser, as far as I know, this behavior is reliable for all browsers that support :before and :after for non-replaced elements, such as a , for which CSS2.1 defines the behavior for these pseudo-elements, as opposed to replaced elements such as img . This makes sense, because if more than one such pseudo-element is to be created, the browser will not know how it should lay them out in the formatting structure.

In the following specificity and cascade a.inactive:before will take precedence, and the :before pseudo-element will have the corresponding content for this link (since both selectors are equally specific - with a type selector, class selector, and pseudo-element):

 a.administrator:before { content: '[Administrator] '; } a.inactive:before { content: '[Inactive User] '; } 
 <a class="administrator inactive" href="profile.php?userid=123">Username</a> 

If an element can match more than one selector with the same pseudo-element, and you want them all to apply in some way, you will need to create additional CSS rules with combined selectors so that you can specify exactly what the browser should in such cases. Extension of the above example:

 a.administrator:before { content: '[Administrator] '; } a.inactive:before { content: '[Inactive User] '; } a.administrator.inactive:before { content: '[Administrator] [Inactive User] '; } 
 <a class="administrator inactive" href="profile.php?userid=123">Username</a> 
+4
Jan 01 '13 at 16:03
source share



All Articles