How do you read the following code snippet? Imagine yourself as a browser.
.note p {
font-style: italic;
}
I guess you will interpret the selector from left to right. This means you will first find a parent element with the note
class. Then, you make all paragraph elements inside it italic. That is wrong, my friend.
A browser will read the selector from right to left. Here are the full steps of a browser reading the above style sheet:
- It will find whether there is a paragraph element. If it can not find any paragraph, there is no reason to figure out the
.note
selector. - If the HTML has paragraph elements, it will capture all paragraph elements and then read the previous selector as a condition, like an if-statement in JavaScript or any other programming language.
- The browser will find an element with the
note
class. If it finds the element, the browser will make all paragraphs inside thenote
class italic.
Now, you understand how a browser reads your style sheet. Ask yourself: what if I write that again inside a media query? You will just add unnecessary tasks for all browsers on this planet. They must repeat those three steps. If you have three media queries, they have to repeat those four times.
Media queries that I am talking about now are the viewport media queries, like the following:
@media (min-width: 40em) {
.grid {
grid-template-areas:
"header header"
"main aside"
"footer footer";
}
}
How do I interpret the code above? For the screen size of 40em
and above, browsers must apply the rules inside this media query.
You should not rewrite the entire base styling inside the media queries. Base styling refers to any Cascading Style Sheets (CSS) code that is outside the media queries. You must not rewrite everything inside the media query. The reasons are the following:
- CSS is smart by default, so you do not need to rewrite everything because not everything needs to be changed. The "C" in "CSS" stands for "cascading." This means it behaves like water, moving from top to bottom. The base styling covers every breakpoint.
- The code inside media queries is specific rules for specific situations.
- Consistency for web design is always appreciated, so you do not need to be afraid to have the same style on different screen sizes.
- Less code is always better. A small codebase is preferable.
- You do not want to look stupid. Yes, you read it right. Moving everything inside a media query is stupid. Only beginners with a lack of knowledge will do that and be proud of that. Stop doing that and learn more about CSS.