Back

Understanding the !important Property in CSS

Understanding the !important Property in CSS

One important concept in Cascading Style Sheets(CSS) is the !important property. This property prioritizes a specific style, overriding other conflicting styles. It can be helpful when you want to ensure that a particular style is applied to an element, regardless of the different styles that may be present. To understand the !important property and its function in CSS, one must first comprehend the notion of specificity in web development, and this article will explain it.

In web development, specificity refers to the set of rules that browsers use to determine which CSS styles should be applied to an element when there are conflicting style declarations. Specificity is calculated based on the weight of the CSS selectors, and it helps browsers decide which style rule should take precedence over others. Specificity ensures that elements on a webpage receive the correct styles. Specificity determines the order in which we apply styles to a component.

Specificity hierarchy refers to the order in which CSS evaluates selectors to determine which styles apply to an element. It helps resolve conflicts when multiple selectors target the same element with different styles.

In CSS, selectors have different levels of specificity, which determines their priority in styling elements. The specificity hierarchy is as follows, from highest to lowest:

  1. Inline style selector: Inline style selector refers to styles applied to an element through the style attribute.
  2. ID selector: The ID selector is a CSS selector used to target and apply styles to a specific element on a web page based on its unique ID attribute. It is denoted by the ”#” symbol followed by the ID value. For example, if you have an element with the ID “myElement”, you can target it using an ID selector like #myElement.
  3. Class, pseudo-class, and attribute selector: Class, pseudo-class, and attribute selectors have the same level of specificity and are, thus, classified as one selector.
  • Class selector: The class selector is a CSS selector used to target and apply styles to multiple elements on a web page that share the same class name. It is denoted by the ”.” symbol followed by the class name. For example, if you have multiple elements with the class “myClass”, you can target them using the class selector like .myClass. This allows you to apply consistent styles to multiple elements with the same class.
  • Pseudo-class selectors: Pseudo-class selectors are CSS selectors that target elements based on their state or position within the document tree. A colon denotes them ”:” followed by the pseudo-class name. Examples of pseudo-classes include :hover, :active, and :first-child. These selectors are used to apply styles to elements when they are in a specific state or meet certain criteria. For instance, you can use the :hover pseudo-class to apply styles to an element when it is being hovered over by the mouse.
  • Attribute selector: Attribute selectors are CSS selectors that target elements based on their attribute values. A bracket denotes them ”[]” and can be used to select elements with specific attributes or attribute values. For example, you can use the attribute selector to target all anchor tags with a particular attribute of href value or all input elements with a specific type attribute value. Attribute selectors provide a flexible way to target and style elements based on their attributes.
  1. Element and pseudo-element selector: Element and pseudo-element selectors have the same level of specificity and are, thus, classified as one selector.
  • Element selector: An element selector is a basic CSS selector that allows you to target and style specific HTML elements on a web page. It selects elements based on their element type. For example, if you want to target all paragraphs on a web page, use the element selector p. This selector will apply styles to all paragraph elements. Element selectors are simple yet powerful tools for styling specific types of elements in CSS.
  • The pseudo-element selector: The pseudo-element selector Is a special type of CSS selector that allows you to target and style specific parts of an element. A double colon denotes it ”::” followed by the pseudo-element name. For example, you can use the ::before pseudo-element selector to add content before an element or the ::after pseudo-element selector to add content after an element. Pseudo-elements give you extra control over the styling of specific parts of a component, allowing for creative and unique designs.

Let’s write a code example using all four selectors to target one element to show a selector that has higher specificity over another.

The element and pseudo-element selector: The element and pseudo-element selector hold the least power. To illustrate, we have employed the <p> element as a selector and have specified a green color for this element. As a result, the text has taken on a green color:

<html>
  <head>
    <style>
      p {
        color: green;
 }
    </style>
  </head>
  <body>
    <p>Hello world!</p>
  </body>
</html>

Result: element

The specified green color for the <p> element was applied in this scenario due to the absence of a selector with higher specificity targeting it. However, in the upcoming example, when we target the <p> element with a selector of higher specificity, it will override the style of the element selector.

Classes, pseudo-classes, and attribute selectors: Classes, pseudo-classes, and attribute selectors are the third level of specificity in CSS. For instance, adding the class selector .example and the specification of a red color for this class would result in the text being rendered in red. This is the case even if a green color is specified for the element selector p. The priority of the class selector is higher than the element selector, which explains the resulting output:

<html>
  <head>
    <style>
      p {
        color: green;
 }
      .example {
        color: red;
 }
    </style>
  </head>
  <body>
    <p class="example">Hello world!</p>
  </body>
</html>

Result: Class

In this particular scenario, the element and class selectors target the <p> element containing the text “Hello world!” The conflicting styles of the two selectors create a competition for application to the targeted element. However, the style specified for the class selector prevails due to its higher specificity level than the element selector.

ID selector: In CSS, IDs serve as the second level of specificity. For instance, the ID selector #example has been added. Due to the priority of the ID selector over the element and class selector, the text will be rendered in blue.

<html>
  <head>
    <style>
      p {
        color: green;
 }
      .example {
        color: red;
 }
      #example {
        color: blue;
 }
    </style>
  </head>
  <body>
    <p class="example" id="example">Hello world!</p>
  </body>
</html>

Result: ID's

The given example illustrates three selectors: element, class, and ID, each targeting the <p> element with distinct font colors specified. However, only the style assigned for the ID selector is applied due to its higher specificity than the other selectors.

Inline style selector: In the present example, an inline style has been incorporated for the <p> element. The text color will appear yellow, overriding other selectors, given that the inline style holds the highest priority in the cascade of styles.

<html>
  <head>
    <style>
      p {
        color: green;
 }
      .example {
        color: red;
 }
      #example {
        color: blue;
 }
    </style>
  </head>
  <body>
    <p class="example" id="example" style="color: yellow">Hello world!</p>
  </body>
</html>

Result: inline-styles

In this scenario, the inline style is prioritized over the other three selectors, and the specified font style is applied to the targeted element.

Equal specificity

When the same selector is present in an external style sheet, the latest selector takes precedence. This means when multiple selectors exist for the same element, the last selector overrides the earlier selector. For instance, we have the following CSS code:

p {
  color: blue;
}
p {
  color: red;
}

When there is a conflict between two selectors, the last selector takes precedence over the first. The <p> element will be rendered in red in this scenario. Class

How to calculate specificity

Calculating specificity helps us understand how CSS rules are applied and how they interact with other styles on web pages. By understanding the specificity of selectors, we can ensure that the intended styles are correctly applied and avoid unexpected styling conflicts.

The table below contains selectors and their specificity values:

SelectorSpecificity Value
Element and pseudo-element1
Class, attribute, and pseudo-class10
ID100
inline style1000
Universal selector0

In calculating specificity, the process begins at 0 and increments by 100 for each ID value, by 10 for each class value (or pseudo-class or attribute selector), and by 1 for each element or pseudo-element, as exemplified below:

<html>
  <head>
    <style>
      p {
        color: green;
 }
      p .example {
        color: red;
 }
      p #example {
        color: blue;
 }
    </style>
  </head>
  <body>
    <p class="example" id="example" style="color: yellow">paragraph</p>
  </body>
</html>

Result: paragraph

Here is the breakdown of the above code:

  • The element selector p has a specificity value of 1 (one element selector)
  • The p.example has a specificity value of 11(one element + one class selector)
  • The p#example has a specificity value of 101 (one element + one ID selector)
  • The inline has a specificity value of 1000

According to the above explanation, you should understand why the specified value for the inline style prevails. The inline style has the highest specificity value of 1000.

The universal selector

The asterisk symbol (*) denotes the universal selector. It targets all elements on a web page, regardless of their type or attributes. It can be used to apply styles globally or as a way to reset or normalize styles across different elements. For example, if you want to apply a specific style to all elements on your webpage, you can use the universal selector in your CSS rule, as shown below:

* {
  /* style rules*/
  color: green;
}

If you notice, the universal selector (*) is not categorized into the specificity hierarchy because it has no specificity value. It applies to all elements equally and does not have specificity weight compared to other selectors like class, ID, or element selectors.

Importance of specificity in web development

Specificity plays a crucial role in web development as it determines the order in which styles are applied to elements. By understanding and leveraging specificity, developers can ensure that the intended styles are correctly applied and avoid conflicts or unexpected styling. Specificity allows for more precise control over the appearance of elements and helps maintain consistency and predictability in the design of web pages.

Having understood the fundamental concepts governing CSS specificity and its mechanisms, we can now examine the !important property and its applicability in web development. However, it is essential to note that this discussion is not covered and that further exploration of CSS specificity may be necessary. For more insight into this topic, refer to an authoritative resource on CSS specificity.

What is the !important property?

The !important property gives a specific style declaration a higher priority over others. It is like saying, “Hey, this style is important, so make sure it takes precedence;” It helps a specific style to override other styles applied to the same element. The !important is added to a CSS property, overriding any conflicting styles. It ensures that a specific style takes precedence, regardless of its position in the stylesheet or specificity.

How to apply the !important property in CSS

To apply the !important in CSS, you simply add it after the property value that you want to give higher priority.

For example, if you want to make a style essential, you would write it like this:

p {
  color: blue !important;
}

By adding !important after the value, ensure this style takes precedence over other styles applied to the same element.

We can go into one more example for better clarity. In this code below, despite having different selectors targeting the same p element, only the inline style was executed because inline styles have the highest specificity among the four selectors.

<html>
  <head>
    <style>
      p {
        background-color: green;
 }
      .example {
        background-color: red;
 }
      #example {
        background-color: pink;
 }
    </style>
  </head>
  <body>
    <p class="example" id="example" style="background-color: yellow">
 Hello world
    </p>
  </body>
</html>

Result: bg-color

But with the !important property, we can prioritize any selectors over others, and its style will be applied to the p element, not minding the position or specificity in the stylesheet:

<html>
  <head>
    <style>
      p {
        background-color: green !important;
 }
      .example {
        background-color: red;
 }
      #example {
        background-color: pink;
 }
    </style>
  </head>
  <body>
    <p class="example" id="example" style="background-color: yellow">
 Hello world
    </p>
  </body>
</html>

Result: important

Despite the element selector having the lowest level of specificity by default, it was able to take precedence over other selectors with the help of the !important property. It is the same with any other selectors with the !important property applied.

Specific use cases of the !important property

Some specific use cases for the !important property include the following:

  • Theme or template framework: Many themes or templates come with predefined styles to give your website or application a consistent look and feel. There may be instances where you want to customize the appearance of certain elements or override the default styles provided by the theme. This is where the !important property helps you to have control over the theme or template framework. It is always a good practice to make use of the !important sparingly as depending heavily on it could lead to CSS code that is hard to maintain.
  • Debugging CSS code: The !important property can be helpful when debugging CSS because it allows you to identify and address style conflicts quickly. By applying the !important property to a specific style declaration, you can ensure that it takes precedence over other conflicting styles. This can help you isolate and troubleshoot issues where styles are not applied as expected. For example, let’s say you have a paragraph element that should have a red font color, but it’s not appearing as intended. By adding the !important property to the font color declaration, like this:
p {
  color: red !important;
}

You can force the paragraph text to be red, overriding any other styles affecting it. If the text turns red, you know a conflicting style in your CSS code preventing the desired color from being applied. In this case, consider changing the order of selectors and removing the !important property from your code base because depending heavily on the !important property could lead to CSS code that is hard to manage and override.

  • Utility classes: A good case could be utility classes. Let us consider a .button class selector with a distinct style: background color, font size, text color, etc. Any element that the .button is applied to should inherit the same style to resemble a button. Let us proceed to style a button component:
<html>
  <head>
    <style>
      .button {
        background-color: blue;
        padding: 10px 20px;
        border-radius: 5px;
        max-width: 300px;
        text-align: center;
        cursor: pointer;
 }
      .button a {
        font-family: sans-serif;
        color: #fff;
        text-decoration: none;
        font-size: 12px;
        font-weight: bold;
 }
    </style>
  </head>
  <body>
    <div class="button">
      <a href="#">Get Started</a>
    </div>
  </body>
</html>

Result button

In some cases, a conflict may arise when the button is put in a container alongside another child element that inherits styles based on the parent element, which possesses greater specificity.

For example, consider a scenario where a button and a login component are situated within a navigation bar container. An anchor element represents the button and login component, and a pre-defined class has already been assigned to the button. Styling the anchor element of the login component based on its parent element leads to a conflict with the anchor element of the button, causing the button to deviate from its intended appearance and inheriting the style of the parent element, which has higher specificity.

For instance:

<html>
  <head>
    <style>
      .button {
        background-color: blue;
        padding: 10px 20px;
        border-radius: 5px;
        text-align: center;
        max-width: 300px;
        cursor: pointer;
 }
      .button a {
        font-family: sans-serif;
        color: #fff;
        text-decoration: none;
        font-size: 12px;
        font-weight: bold;
 }
      #navbar {
        display: flex;
        flex-direction: column;
        gap: 10px;
        margin: 30px 20px;
        font-family: sans-serif;
 }
      #navbar a {
        text-decoration: none;
        color: blue;
        font-size: 12px;
 }
    </style>
  </head>
  <body>
    <div id="navbar">
      <a href="#">Login</a>
      <div class="button">
        <a href="#">Get Started</a>
      </div>
    </div>
  </body>
</html>

Result:

affected button

Looking at the button, it no longer appears as intended. The anchor element has two different selectors targeting it when it gets into the navbar container, and because the navbar container has a selector of higher specificity, it affects the original style of the button element, causing the button to lose its original appearance, changing the button’s initial font color(white) to the font color of the navbar container(blue). This is where the !important property comes in handy, so we can override the conflicting style to achieve the button’s original style.

In this code below, we will add the !important to the button font color to override the conflicting style:

<html>
  <head>
    <style>
      .button {
        background-color: blue;
        padding: 10px 20px;
        border-radius: 5px;
        text-align: center;
        max-width: 300px;
        cursor: pointer;
 }
      .button a {
        font-family: sans-serif;
        color: #fff !important;
        text-decoration: none;
        font-size: 12px;
        font-weight: bold;
 }
      #navbar {
        display: flex;
        flex-direction: column;
        gap: 10px;
        margin: 30px 20px;
        font-family: sans-serif;
 }
      #navbar a {
        text-decoration: none;
        color: blue;
        font-size: 12px;
 }
    </style>
  </head>
  <body>
    <div id="navbar">
      <a href="#">Login</a>
      <div class="button">
        <a href="#">Get Started</a>
      </div>
    </div>
  </body>
</html>

Result: navbar

By adding the !important property to the font color of the button, we override the conflicting style to maintain the original style of the button component.

Pros of using the !important property

When it comes to the !important property, there are a few pros to consider:

  • Priority: The !important property gives your CSS declarations the highest priority, overriding any conflicting styles. This can be useful to ensure that a specific style is applied consistently across your website.
  • Flexibility: With the !important property, you have more control over your CSS styles. It allows you to easily override styles from external stylesheets or frameworks without modifying their source code.
  • Accessibility: The !important property can help make your website more accessible. It allows you to prioritize certain styles that enhance readability or accommodate users with visual impairments.

Cons of using the !important property

When it comes to the cons of using the !important property, here are a few things to consider:

  • Specificity issues: The !important property can sometimes create specificity conflicts. If multiple styles have the !important declaration, it can become challenging to determine which style should take precedence. This can make maintaining and updating your code hard.
  • Overriding difficulties: Once you use the !important property, it can be difficult to override that style later on. This can make it harder to change and modify your CSS in the future. It may require additional effort and workarounds to overcome the specificity set by the !important property.
  • Code maintainability: Using the !important property extensively, makes your code less maintainable. It becomes hard to understand and debug the CSS, especially for other developers who may work on the same project. Always keep your codebase clean and organized for easier maintenance and collaboration.

Browser compatibility

The image below shows the browsers that support the !important property.

Screenshot_19-5-2024_2367_caniuse.com

source

When it comes to browser compatibility, the !important property is widely supported by modern browsers. It is recognized and applied consistently across browsers such as:

  • Chrome
  • Firefox
  • Safari
  • Edge, etc.

So you shouldn’t encounter browser compatibility issues using the !important property. However, it’s always a good practice to test your CSS styles across different browsers to ensure consistent rendering.

Best practice and consideration when using the !important property

When it comes to using the !important property in CSS, there are some best practices and considerations to keep in mind:

  • Maintaining a clean and organized CSS code base: Using the !important property sparingly and only when necessary. Overusing !important can make your styles hard to manage and maintain, making code difficult to read and understand.

  • Strategy to avoid excessive use of !important property: One strategy for avoiding excessive use of !important is to use more specific selectors. Making your selectors more specific ensures that your styles are applied correctly without relying on the !important property. This can help prevent style conflicts and make your code more maintainable in the long run.

  • Understanding the implications of using the !important property on code readability and maintainability: It’s also crucial to understand the effects of using the !important on code readability and maintainability. When the !important is used, it overrides any other conflicting styles, including those defined by the theme or template. This can lead to unexpected behavior and make issues in your CSS code hard to debug and troubleshoot. It’s generally recommended to prioritize specificity and organization in your CSS code. By following best practices like using consistent naming conventions, organizing your styles logically, and commenting on your code, you can make it easy for yourself and others to understand and modify your CSS code in the future.

Conclusion

In this article, we learned about CSS specificity, which denotes the criteria that specify the styles applied to an element when multiple styles have been defined for the same element. Learning CSS specificity helps us grasp the concepts of the !important property, which gives a specific style higher priority than others. It’s often used as a last resort to override other styles.

When you apply the !important declaration to a CSS property, the property overrides any conflicting styles, even if they have higher specificity or are defined in the same stylesheet. We also noted the importance of using the !important property sparingly and only when necessary, as it can make your styles harder to maintain and override.

Truly understand users experience

See every user interaction, feel every frustration and track all hesitations with OpenReplay — the open-source digital experience platform. It can be self-hosted in minutes, giving you complete control over your customer data. . Check our GitHub repo and join the thousands of developers in our community..

OpenReplay