CSS Class Override: How To Add Custom Styles The Right Way?

Tags
14 November 2023
Complete Guide for CTO & IT Directors
Microservices under X-Ray Three books image Download free ebook

In CSS, class overriding allows developers and designers to control web page styles. Find out how it works and how to use it for adding custom styles.

CSS (Cascading Style Sheets) is a language used to style documents written in markup languages, such as HTML, XHTML, or SVG. It defines styles for web pages and describes how elements should be displayed on the screen.

With CSS, you can set colors, font styles, spacing, and other visual aspects of a web page, adjusting layout and display variants for different screen sizes.

By separating HTML-based structure and content from the presentation layer, web designers can create visually appealing and responsive websites with a consistent user experience across devices and browsers.

Sometimes, though, an HTML element cannot be easily modified. It can be due to several reasons, some of which relate to CSS properties inheritance.

What is inheritance in CSS?

Inheritance is the mechanism of reusing base class code in a subclass. It helps keep code concise by referencing already defined values instead of defining them anew. In CSS code, inheritance determines how certain properties and styles are passed down from parent to child elements in the HTML document’s structure.

Inheritance works by default for some CSS properties, but many are not inherited automatically. Properties falling into the first category include azimuth, font-style, font-weight, font-family, line-height, letter, word, and border spacing, and more.

Those in the second category include background color, min/max-height, border-style, bottom, background, and many others. You can check the full list HERE.

Creating a consistent styling pattern for non-inherited properties across multiple elements requires manually applying those styles to each element individually. Fortunately, it can be facilitated by using classes or other selectors to target specific elements and set their styles.

For example, let’s say you want to apply a specific width and background-color to multiple <div> elements:

/* Apply styles to specific div elements */

.custom-div {

  width: 200px;

  background-color: #f0f0f0;

}
<div class="custom-div">Element 1</div>

<div class="custom-div">Element 2</div>

<div class="custom-div">Element 3</div>

In this example, you create a class called .custom-div and apply it to each <div> element where you want to enforce specific styles. This approach allows you to achieve consistent styling for non-inherited properties across those elements.

Overriding CSS style

Inheritance makes things easier. However, it can cause difficulties when developers want to style child elements differently from their parents.

For example, if the font color is inherited, child elements will have the same color as their parent. But suppose you want to make it different. You need to override one CSS style with another one with a higher specificity.

p {

  color: blue; /* Parent element sets font color */

}

p span {

  color: red; /* Child element inherits parent's color but is overridden */

}

This operation is known as CSS override or overriding CSS style. It consists in modifying or replacing existing CSS rules or styles with new ones to change the appearance or behavior of HTML elements on a web page. This is typically done to achieve customization or responsiveness or to address specific design requirements.

How does cascading order work in CSS?

Style overrides are also necessary when a conflict occurs between two different styles applied to the same element for reasons unrelated to inheritance.

In this case, CSS uses a cascading order of style sheets ranked by priority:

  • browser defaults,
  • external style sheets (imported or linked style sheets),
  • internal style sheets (embedded style sheets),
  • inline styles.

In other words, when two styles come into conflict, the winner is the one with the higher priority (is lower on the list above).

How to override CSS style?

So, how to apply CSS overrides? It can be done in several ways.

Increasing specificity

CSS rules with higher specificity take precedence over rules with lower specificity. You can leverage selector specificity by using more specific selectors or adding more selector components (types, CSS classes, ID, pseudo-classes, etc.). For example, an ID selector (#element-id) is more specific than a class selector (.element-class), and inline styles have the highest specificity. Here’s an example of how you can increase specificity by adding more selector components to your rule.

/* Original selector */

.element-class {

  color: blue;

}

/* More specific selector - overrides the original rule */

.parent-element .element-class {

  color: red;

}

In this example, the second rule has a higher specificity because it includes both the class selector (.element-class) and a parent element selector (.parent-element).

Inline styling

Inline styling allows you to apply styles directly to individual HTML elements within their HTML tags. Inline styles have the highest specificity and will override any external or internal style sheets. The style attribute contains one or more CSS property-value pairs enclosed in double quotes (“). Each property-value pair should be separated by a semicolon (;).

<element style="property1: value1; property2: value2; ...">

  Content

</element>

Here’s a small example of inline CSS styling. Let’s say you have the following CSS styles defined in your stylesheet:

.element-class {

  color: blue;

  background-color: yellow;

}

You can override these styles for a specific element using this inline style code:

<div class="element-class" style="color: red; font-size: 16px;">

  This text is red with a font size of 16px.

</div>

In this example, the color property is overridden with the value red, and a new property, font-size, is added to the element.

Inline styles have the highest precedence and will always override conflicting styles from external style sheets or internal styles. This is because inline styles are applied directly to the HTML element and have higher priority than all other styles.

Inline CSS styles are particularly useful when you need to make quick and specific changes to individual elements without modifying the overall stylesheet. It’s commonly used for applying dynamic styles based on user interactions, customizing the appearance of specific elements, and fixing styling issues or overrides that cannot be achieved through external CSS styles.

Order of styles

Increasing specificity as a means to override CSS style meets its limit when conflicting rules are on par. In such a case, the order decides. As has already been mentioned, when multiple CSS rules apply, the cascading order governs the precedence. Rules defined later in the style sheet or closer to the element in the HTML document will override earlier rules with the same specificity. Here’s how it looks in CSS code:

/* Earlier rule */

.element-class {

  color: blue;

}

/* Later rule - overrides earlier rule */

.element-class {

  color: red;

}

!Important attribute

A common way of CSS overriding is the !important declaration. As the name suggests, enhancing styling with the !important keyword causes it to override all other rules, regardless of specificity or the order of declaration. The attribute is added directly to a CSS property within a style rule at the end of the styling instruction line, like in the example below.

.element-class {

  color: blue !important;

}

!important is a handy rule, but developers tend to overuse it. It’s a good practice to apply the attribute only when necessary since getting too “!important-happy” may lead to site-wide issues and make CSS harder to maintain

Essentially, the !important instruction is reserved for situations where you need to ensure a particular style always applies, such as when working with third-party libraries or when dealing with styles that cannot be changed through normal means.

Latest Posts

Scrum: How to Work Together

With the popularity of the scrum framework among software development teams, it’s growingly important to learn how a scrum team works to meet its goals. Scrum Process Overview Scrum is an agile project management framework widely used in IT but can be applied to other fields as well. The framework facilitates the management of complex […]

/
event storming

Event Storming: How to Boost Your Software Development Process with a Simple Technique?

Event storming is a dynamic workshop technique that supports domain-driven design in software development. It can boost the team’s efficiency and reduce error risk, minimizing the back-and-forth in the development lifecycle. If you haven’t been living under a rock, you’re probably familiar with the concept of brainstorming. It’s a widely used term for the process […]

/
rails vs sinatra

Rails vs Sinatra

In the rapidly evolving world of software development, web frameworks have become essential tools for building robust and scalable web applications. These frameworks provide a structured environment that streamlines the development process, offering pre-written code, libraries, and guidelines that help developers avoid repetitive coding tasks, thus significantly enhancing productivity and ensuring best practices. Within the […]

/
android webstockets

Introduction to Android WebSocket

WebSockets have become a pivotal technology in enabling real-time communication for Android apps, offering a dynamic way to send and receive messages instantaneously. This technology facilitates a persistent connection between the client (Android app) and the server, bypassing the traditional HTTP request-response model to allow continuous data flow through a single TCP connection. The WebSocket […]

/
smart contracts audit

Introduction to Smart Contract Audits

In the blockchain world, smart contracts are key to decentralized applications (dApps), automating transactions and enforcing agreements without intermediaries. These contracts handle significant digital assets and perform crucial operations, making their security paramount. Smart contract audits are thus essential, scrutinizing the contract’s code for vulnerabilities to prevent potential security breaches. These audits are crucial for […]

/
What is Python Used for in Finance

Embracing the Essence of Scrum: The Indispensable Values for Agile Teams

In the ever-evolving landscape of project management, Agile methodologies like Scrum have become the cornerstone for many teams striving for adaptability and efficiency. While Scrum offers a comprehensive framework and great agile tools, it is the underlying values that truly breathe life into the process. During The Sprint What Scrum Value Must The Team Demonstrate […]

/
Related posts
rails vs sinatra

Rails vs Sinatra

In the rapidly evolving world of software development, web frameworks have become essential tools for building robust and scalable web applications. These frameworks provide a structured environment that streamlines the development process, offering pre-written code, libraries, and guidelines that help developers avoid repetitive coding tasks, thus significantly enhancing productivity and ensuring best practices. Within the […]

/
rxjs react

RxJs & React: Reactive State Management

In the ever-evolving realm of web development, the quest for efficient, scalable, and maintainable tools never ends. Two such tools, React and RxJS, have garnered significant attention in the recent past. React, the brainchild of Facebook focuses on crafting intuitive user interfaces by leveraging a component-based architecture. On the other hand, RxJS offers a fresh […]

/
css class override

CSS Class Override: How To Add Custom Styles The Right Way?

In CSS, class overriding allows developers and designers to control web page styles. Find out how it works and how to use it for adding custom styles. CSS (Cascading Style Sheets) is a language used to style documents written in markup languages, such as HTML, XHTML, or SVG. It defines styles for web pages and […]

/
angular advantage

Advantages of Angular in Web Development

Angular is one of the most widely used frameworks for building amazing UIs. It can speed up the development process and save a lot of costs. Find out about its features, key advantages, and limitations. Angular is a leading open-source front-end framework for developing web applications and one of the most popular software development tools […]

/
django vs flask

Django vs. Flask. Which framework will work better for your web development project?

Flask and Django are the top two Python frameworks for web development. They are different in many ways, but both can provide great results in the hands of skilled software engineers. We’ve compared Flask vs. Django to figure out what their superpowers are. The Python programming language has been experiencing a rapid rise in popularity […]

/
dependency injection python

Dependency Injection in Python Programming

Dependency Injection (DI) is a design pattern used in software development to reduce coupling between components and improve code maintainability, testability, and scalability. In this blog post, we will explore the concept of Dependency Injection, its advantages in Python, how to implement it, and best practices for using it effectively. What is Dependency Injection (DI)? […]

/
Talk with experts

We look forward to hearing from you to start expanding your business together.

Email icon [email protected] Phone icon +1 (888) 413 3806