As we mentioned in the previous section, you need a selector when you are writing a CSS rule. Selectors are used to indicate which HTML element you are styling. The most fundamental selector would be the element selector (also called a tag, or type selector) p, h1, h2, etc. This allows you to select all HTML elements of the specified element type.
language=>HTML
<p>...</p>
<p>...</p>
language=>CSS
p {
color: red;
font-size: 15px;
}
To customize just one element, say a particular paragraph, you can use an ID selector. ID is an attribute that you can add to element tags. On a given HTML page, you are only allowed one element per ID. You should reserve using ID only for important elements. To use ID as selectors, simply place a hashtag # sign at the beginning of the ID attribute value.
language=>HTML
<p id="special-paragraph"></p>
language=>CSS
#special-paragraph {
color: green;
font-size: 20px;
}
What if you want to apply styles to a small group of paragraphs, maybe those are useful notes that you want to stand out for a holiday trip you are writing about. Class selector would be what you are looking for. Class is an attribute that you can add to multiple HTML tags, and your CSS styles will apply to all elements with the same Class attribute value. To use Class as a selector, add a period . to the beginning of the Class attribute value.
language=>HTML
<p class="useful-notes">...</p>
<p class="useful-notes">...</p>
<p class="useful-notes">...</p>
language=>CSS
.useful-notes {
color: blue;
font-weight: 400;
}
You can define the same style for multiple selectors by using a comma , to join them.
language=>CSS
p, h1, h2 {
font-family: Serif;
}
There are more advanced selectors than the ones described above, we will learn them as we go along.
Properties and Values
The things we put between the curly brackets {} are called Properties. They are what we use to define the styles of the selector. There is a large number of properties, below are some of the common ones we use for text elements. We will look into each category of properties in later chapters.
language=>CSS
p {
font-style: italic;
font-variant: small-caps;
font-weight: 400;
font-size: 14px;
font-family: sans-serif;
line-height: 3;
}
One thing to mention is that some properties have a shorthand rule. Which means you can use one property and multiple values to set the styles for multiple properties. For the font, it is simply font. It allows you to define all the font properties in one line.
language=>CSS
p {
/* style | variant | weight | size/line-height | family */
font: italic small-caps 400 14px/3 sans-serif;
}
Let's put what we learned into practice with the following exercises.
Exercise - Only do the following exercises