Tips#2. How One Style Prioritize Over Another | CSS
Sometimes your HTML elements will receive multiple styles that conflict with one another. Let explore them and understand step by step
1. Applying css color to body only
Remember, you can style your body
element just like any other HTML element, and all your other elements will inherit your body
element's styles.
<style>body{color:#dedede;}</style><h1>Hello World!</h1>
2. Applying color using class
Our “brown-text” class override our body
element's CSS declaration!
<style>body {background-color: black;font-family: monospace;color: green;}.brown-text {color: brown;}</style><h1 class=”brown-text”>Hello World!</h1>
3. Applying multiple class attributes to a HTML element
Note: It doesn’t matter in which order the classes are listed in the HTML element.
However, the order of the class
declarations in the <style>
section are what is important. The second declaration will always take precedence over the first.
<style>body {background-color: black;font-family: monospace;color: green;}.brown-text {color: brown;}.red-text{color:red;}</style><h1 class=”brown-text red-text”>Hello World!</h1>
Browsers read CSS from top to bottom. That means that, in the event of a conflict, the browser will use whichever CSS declaration came last.
But we’re not done yet. There are other ways that you can override CSS. Do you remember id attributes?
4. Applying css using id attributes
Note: It doesn’t matter whether you declare this CSS above or below class, since id attribute will always take precedence.
<style>body {background-color: black;font-family: monospace;color: green;}.brown-text {color: brown;}.red-text{color:red;}#blue-text{color:blue;}</style><h1 id="blue-text" class="brown-text red-text">Hello World!</h1>
5. Overriding with inline-style css
id declarations override class declarations, regardless of where they are declared in your style
element CSS.
But we just proved below that inline styles will override all the CSS declarations in your style
element.
<style>body {background-color: black;font-family: monospace;color: green;}.brown-text {color: brown;}.red-text{color:red;}#blue-text{color:blue;}</style><h1 id="blue-text" style="color: yellow;" class="brown-text red-text">Hello World!</h1>
6 . Override All Other Styles by using Important
Note: This is the most powerful method of all. But before we do it, let’s talk about why you would ever want to override CSS.
In many situations, you will use CSS libraries. These may accidentally override your own CSS. So when you absolutely need to be sure that an element has specific CSS, you can use
!important
<style>body {background-color: black;font-family: monospace;color: green;}.brown-text {color: brown;}.red-text{color:red !important;}#blue-text{color:blue;}</style><h1 id="blue-text" style="color: yellow;" class="brown-text red-text">Hello World!</h1>
Thanks