Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding CSS class on pseudo-element

Tags:

I was wondering if there's a way to add a CSS class to pseudo-elements, such as :after.

I want to use :after to append an error message. I also want the error message styled the same way as the other error messages.

This works:

.error:after {
  content: "Error Message";
  color: red;
}

But can I do something like this to add more than the color styling?:

.error:after {
  content: "Error Message";
  class: error_message_styles;
}

Also, is there a difference between using "::after" vs ":after"?

Thanks in advance!

like image 732
Zhao Li Avatar asked May 15 '12 21:05

Zhao Li


People also ask

Can CSS classes combine with pseudo-classes?

If you're talking about pseudo-classes, then yes, you can combine them in any order.

What are CSS pseudo-classes?

A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :hover can be used to change a button's color when the user's pointer hovers over it.

When would you use the :: before or :: after pseudo-element in your CSS?

Special welcome offer: get $100 of free credit. CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.


2 Answers

There's no way to give an HTML attribute of any kind to a psuedo element.

Just use the selector twice:

.error:after {
  content: "Error Message";
}
.error:after, .error-style {
  color:red;
}

Also, is there a difference between using "::after" vs ":after"?

According to this:

https://developer.mozilla.org/en/CSS/:after

The ::after notation was introduced in CSS 3 in order to establish a discrimination between pseudo-classes and pseudo-elements. Browsers also accept the notation :after introduced in CSS 2.

Note: Microsoft Internet Explorer 8 supports the :after notation only.

I would argue that error messages might be content, not decoration - but that's your call.

like image 130
Wesley Murch Avatar answered Sep 27 '22 22:09

Wesley Murch


The :after element is not a physical DOM element, so it can't take a class.

If you use a stylesheet library like LESS, you can mix in the styles from other classes by including the class as a property:

.error {
    .error-styles;
}
like image 34
JoeJ Avatar answered Sep 30 '22 22:09

JoeJ