Sumit | Javascript + React
Sumit | Javascript + React

@sumitsaurabh927

11 Tweets 3 reads Mar 02, 2023
๐Ÿ“Œ CSS: Conflicts, cascading, and more!
๐Ÿงต A thread: ๐Ÿ‘‡
Continuing our journey from the basics of CSS, we'll today learn about:
- What is cascading?
- What happens when CSS rules conflict with each other?
- How to resolve conflicts?
If you wanna take a look at yesterday's thread, you can check it out here:
But first, let's take a look at what cascade means.
See, in web dev, we've 3 ways to apply CSS rules to HTML. They are:
1. Internal CSS - writing CSS in 'style' tag in HTML
2. Inline CSS - writing CSS as attributes of HTML tags.
3. External CSS - writing CSS in an external file
So, one HTML element can have multiple CSS rules written for it. This causes cascading of CSS rules.
Well, that's easy. Just use only one way to write CSS and avoid it altogether.
Hmmm, it looks plausible but it doesn't quite work that way...๐Ÿ‘‡
You see, the hierarchy of CSS rules is as follows:
- Default CSS (by the browser)
- User-defined stylesheet
- External CSS
- Page-specific CSS
- Inline CSS
And even if we were to write CSS using just one way, we can still write multiple CSS declarations for one HTML element.
And when we have a situation where there are multiple CSS rules for one HTML element, which rule is going to be applied to it, is determined by the cascade.
There are three factors that determine this:
1. Specificity
2. Inheritance
3. Order of appearance
Let's look at them..๐Ÿ‘‡
1. Specificity:
CSS selector with higher specificity scores is the one that gets precedence over the one with lower specificity.
Specificity scores of different selectors are as follows:
1. ID selector - 100
2. Class selector - 10
3. Type selector - 1
4. Important flag - 1000
2. Inheritance:
Properties that an element gets because some CSS rules were applied to its parent.
Most CSS rules are not inherited but some text properties such as font-family and font size are inherited.
If the child element is targeted directly, then this doesn't apply.
3. Order of appearance:
All the above-listed rules are fine but what happens if two selectors have the same specificity scores?
Well, in such tie-breaker situations, the rule that was written last wins.
This is like a waterfall, the last one wins!
Lastly, note that although we can write CSS rules in multiple ways as specified above, writing it in an external file is the most preferred way of writing CSS.
So, unless you have specific reasons not to do that, always write CSS rules in an external file.
That's a wrap!
If you enjoyed this thread:
1. Follow me @sumitsaurabh927 for more of these
2. RT the tweet below to share this thread and show me some love! ๐Ÿงก๐Ÿงก๐Ÿงก

Loading suggestions...