For many people, CSS is a tough beast to tame, especially if you come from other languages. You can change a line and break the entire site!
But don’t worry! There are four keys that will make you easier to understand how CSS works.
The first one is that CSS is a declarative language. Most languages (JavaScript, for example) are imperative. That means that you write the actions to be done: display a message, send an HTTP request, etc. In declarative languages, what you do is to describe the final result.
The second keyword is inheritance. That is, child elements inherit many (not all) the styles from the parent. For example, if you have the following code:
/* CSS */
div.blueContainer { color: blue }
<!-- HTML -->
<div class="blueContainer">
<h1>Hello world!</h1>
Lorem ipsum dolor
</div>
The text “Lorem ipsum dolor” will look blue, but the h1
heading will be blue too, because it inherits the font styles from its parent, the div
with the class blueContainer
.
Not all properties are inherited. borders, margins, paddings, width, and height are not inherited, for example.
The third keyword is specificity. There are many cases where two conflicting styles apply to the same element. For example:
/* CSS */
h1 { color: red }
article h1 { color: blue }
<!-- HTML -->
<article>
<h1>Hello world!</h1>
Lorem ipsum dolor
</article>
In the example above, there are two rules that might apply to the h1
heading. One that says the heading should be red, and another one says it should be blue! Then conflict happens, the more specific rule prevails.
The first rule applies to every h1
heading, but the second rule applies only to those headings inside an article
tag. Therefore, the more specific second rule prevails and the heading will be blue.
When dealing with specificity, there are also a couple of rules:
- Class selectors are more specific than element selectors
- The combination of element and class selector (e.g.
h1.heroTitle
) is more specific than a class selector alone (e.g..heroTitle
) - ID selectors (e.g.
#uniqueElement
) is more specific than other type of selectors
The fourth keyword is order of appearance. What happens when two rules with the same specificity affect the same element? The answer is, the styles from the last rule override the previous ones. Let’s see an example:
article h1 {
text-decoration: underline;
color: purple;
}
article h1 {
color: red;
}
<article>
<h1>Lorem Ipsum</h1>
</article>
Here, the h1
heading will be underlined, because the text-decoration: underline
property from the first rule is not overriden by the second rule. But this heading will be red, because the second rule, which is just as specific as the first one, overrides it.