Pseudo-Classes and Relationships - Chapter 5
➜ Chapter Booklet HERE
Pseudo-Classes and Relationships
You know, from our discussion in our first course, that just about every element is nested inside of other elements (i.e., the body element is inside of the html element, paragraph and heading elements are inside of the body element, etc.)
All of this nesting creates relationships and they are typically referred to as parent-child relationships. Thus, if an element has another element directly within it, the nested element is the child of the first element and if there are other elements within the child, then they are called descendants of the first element.
<div> (Parent)
<p> Something here. (Child)
<h2>Something here.</h2> (Descendant)
</p>
</div>
These relationships can be managed with CSS to render styles for various elements. For example:
div > p {
color: red;
}
(Child Selector)
The above code would take every <p> element in the HTML file, that’s a direct child of a <div> element, and make its text red. It doesn’t matter if there are other <p> elements in the HTML file, the CSS rule will ONLY apply to those <p> elements that are direct children of a <div> element—this is called a Child Selector.
div h2 {
color: white;
}
(Descendant)
Now, let’s say I only wanted to select the <h2> element that is in this <div>. This <h2> element is not a direct child of the <div>, but it is a descendant. All I would have to do is put a space, instead of a >, and that would select any <h2> that was a descendant of the <div> and apply that style to them.
This comes in handy when we want to style a navigation bar because they inevitably have nested elements.
<nav class="navbar"> <ul>
<li><a href="index.html">Home</a></li>
<li><a href="about_me.html">About Me</a></li>
<li><a href="#">Background</a></li>
</ul> </nav>
We are going to have to use descendant selectors to style the list items in our navigation bar, while not affecting the other list items that are in our page.
Pseudo-Classes
This next topic also comes in handy when we need to style a navigation bar.
Pseudo-classes allow you to apply style to an element when it is in a certain state. For example, if you’ve ever clicked on a link in a webpage and noticed that the link changed colors in the navigation menu once you visited the linked page, then you’ve experienced a pseudo-class in action.
The link (or <a> element) was styled with CSS to change colors once the page had been visited. You can also make an <a> element change colors when someone hovers over it with a cursor. To use a pseudo- class you write:
In the HTML file:
<ul>
<li><a href=“page">Words</a></li>
</ul>
In the CSS file:
a:hover {
color: red;
}
(Pseudo-class)
You use a colon to designate a pseudo-class in combination with the element to which you want to apply that style.
Let’s try all of this out in our navigation menu.
Be sure to complete the exercise for this chapter, before moving on to the next chapter.