Selector types

Element selector

An example of an element selector is:

body {
	font-size: 22px;
}

This means that it will apply the CSS rules to all elements of that type - this could be applied to all p elements, too, for instance.

Class selector

.gray {
	color: gray;
}

Class selectors are defined by using the period notation. We can apply each class to our HTML code with the class attribute.

Generally classes are more specific and they will ovewrite the element selectors.

ID Selector

#second {
	font-style: italic;
}

ID selectors are prefixed with #, and they are the most specific selector. However, in general we should avoid using ID selectors in our CSS.

Applying selectors

We can apply selectors to multiple elements by simply declaring it on the CSS file as follows:

h1, h2, p, section {
	color: blue;
}

Nested selectors

If we apply the selectors as above, but without the commas, we are nesting the selectors. For instance:

h1 h2 {
	color: purple;
}

This will look specifically for h2 tags nested inside h1 tags

Notes:

  • CSS Selectors have inheritance.

Application order

CSS will apply rule sets from top to bottom, but specificity will override the cascade of rules: for instance, declaring two different p elements will mean that the second overrides the first. However, a class that is applied to the same p elements will always win, even if it is declared first.

Inheritance

In CSS every element will inherit some properties from its parent element. Thus, applying something to, say, body will apply it to everything inside the body. The things applied are stuff like:

  • Font
  • Font color
  • Spacing
  • Anything related to typography, generally

Note that form elements, like button, input, textarea, etc don’t inherit typography elements. In either the case of these elements or any other, we can explicitly inherit using the inherit keyword:

button, input {
	font: inherit;
}