Taught by Tina May
So far we’ve learned CSS properties to change sizes, color & background color, style typography, and play with negative space. And we’ve done it with our simple CSS syntax where we have our selector, and then at least one property and the value.
And so far we’ve used the element selector, where we select all of the paragraph elements, or all of the h2 elements, or all of the images and we style them together. I know some of you are starting to wonder, how do we style just some of the headings or one particular image?
And that’s what we’re going to learn today, two new kinds of selectors to get more specific in the elements that we’re styling.
One of the common ways you might want to style elements is by only targeting those that are inside another element. For example, you might want to style all of the anchor links <a>
that are inside your <header>
element or all of the h2 headings that are inside your <article>
.
We can do that with a simple CSS selector that we call the child selector, and what it says to the browser is “target my only ______ element that is inside the ______ element”.
We put the parent first, and then the child second separated by a space.
The thing about this selector is that the target doesn’t have to be the direct child, it can be a “grandchild” or the child inside the child of the parent element and that still counts. So think about it more as a descendant selector.
The next selector we can work with is our class selector. Classes in CSS are used to create reusable styles. When we’re designing, we try to create consistent patterns or styles that we use in different parts of the website. CSS classes help us to group different parts together and apply the same CSS properties to all of them.
Class selectors have two parts. First, we need to apply the class to the elements that we want to style in the HTML, by adding a class attribute.
<p class="classname"> ... </p>
So for example, if we wanted to create a paragraph with a class of .alert
we would say:
<p class="alert">Lorem ipsum dolor sit amet.</p>
Then when we go over to our CSS we can target all our elements with a class of alert with our class selector, which is just a full stop (.) followed by the class name.
/* This will style all of elements with a class of alert */
.alert {
background-color: orange;
color: white;
}
A few things to note about classes:
<h1 class="alert padded-5">Hello everyone</h1>
<p class="alert">I can never think of clever things to write.</p>
<p>Too busy focused on teaching you to code!</p>
<p>Help! I forgot my closing tag!!</p>
<p class="text-align-right">Sincerely,<br>Tina</p>
.alert {
background-color: orange;
color: white;
}
.padded-5 {
padding: 5%;
}
.text-align-right {
text-align: right;
}
Have fun and show us what you come up with in the discussions (the blue chat icon on the right). Need a bit of a sneak peak? I've created a codepen with the HTML structure already started for you.