DEV Community

parayan Sharma
parayan Sharma

Posted on

How To Override CSS Style?

To override CSS styles, you typically need to apply a more specific or equally specific selector with the desired styles. Here are a few common ways to do this:

  1. Using !important: You can add !important to a style to give it higher specificity and priority. However, this should be used sparingly because it can make your CSS harder to manage and maintain.
   .my-class {
     color: red !important;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Increasing specificity: If you have conflicting styles, you can increase the specificity of your selector to override others. For example, adding an additional class or an ID.
   .parent .my-class {
     color: red;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Inline styles: Inline styles always take the highest precedence, so you can add styles directly to the HTML element.
   <div style="color: red;">This text is red.</div>
Enter fullscreen mode Exit fullscreen mode
  1. Using IDs: IDs have higher specificity than classes, so using an ID selector can override styles.
   #unique-element {
     color: red;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Using parent elements: Sometimes you can use a parent element to target a specific child.
   .parent .child {
     color: red;
   }
Enter fullscreen mode Exit fullscreen mode
  1. Using the :not() selector: If you want to target everything except a specific class, you can use the :not() selector.
   .my-class:not(.special) {
     color: red;
   }
Enter fullscreen mode Exit fullscreen mode

Remember that the order of CSS rules matters. If two rules have the same specificity, the one that comes last in the stylesheet will take precedence. It's good practice to keep your styles organized and avoid relying too heavily on !important to prevent unintended consequences.

Top comments (0)