Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Ignore and acknowledge class attribute on elements in CSS

Sometimes, when working with some common elements, for instance, <ul>, <a>, or <div>, you might add the class attribute to some of them and then use that class to style them.

Many times, these classes might be different for the same kind of elements. For instance, <ul> might have a class of list and some-other-list for different lists. These classes have different styles according to the context.

But sometimes, what you might really want is to have common styles for these elements irrespective of the class they have.

For instance, if you want to apply a common style to all <ul> elements with the class attribute (i.e. to acknowledge the class attribute), you can do that by using the [class] selector in CSS like so.

ul[class] {
  /* common styles */
}

This will apply the common styles to all <ul> elements with the class attribute.

On the contrary, if you want to apply a common style to all <ul> elements without the class attribute (i.e. to ignore the class attribute), you can do that by using the :not([class]) selector like so.

ul:not([class]) {
  /* common styles */
}

This will apply the common styles to all <ul> elements without the class attribute.

Here’s a CodePen to demonstrate this.

See the Pen Ignore and acknowledge class on elements by Amit Merchant (@amit_merchant) on CodePen.

By the way, the [attribute] selector can also be used on other attributes like id, href, src, etc as well.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?