override css style
Code snippet for how to override css style with sample and detail explanation
Override CSS Style
CSS is the language for describing the look and formatting of a document written in HTML. As developers or designers, we often find ourselves in situations where we need to override the existing CSS styles. This post will guide you through the process of overriding CSS styles.
Code snippet for Overriding CSS Styles
<style>
.parent .child {
color: blue;
}
.override {
color: red !important;
}
</style>
<div class="parent">
<p class="child">This text is blue.</p>
<p class="child override">This text is red.</p>
</div>
This code snippet demonstrates the process of overriding CSS styles in an HTML document.
Code Explanation for Overriding CSS Styles
In the code snippet, you’ll see two CSS rules defined within the <style>
tags. The first rule determines that any element with a class child
that is contained in an element with a class parent
will have the color blue.
The second rule is where the overriding of styles happens. The override
class is given a color value of red with the !important
rule attached to it. The !important
rule is a way to make your CSS rule take precedence over other rules that might apply to the same element. In this case, whenever we use the override
class, it will take precedence over the child
class and change the text color to red.
Once you move to the HTML structure, you have two paragraphs in a div
with class parent
. The first paragraph has only child
class and the text color is blue as specified in CSS.
The second paragraph has two classes - child
and override
. According to the CSS styles, this is supposed to be blue (following child
class), but due to the presence of override
class and the !important
rule in CSS, the original style is overridden, and the text color for this paragraph becomes red.
This is how to override CSS styles. It’s a common practice especially when you’re dealing with third party libraries, but use the !important
rule judiciously, as it can make debugging CSS issues more challenging.