...

/

CSS Selectors - again!

CSS Selectors - again!

In this lesson, we will take a look at descendant selectors, combinator selectors and pseudo class selectors. While these may seem strange to you now, I'll show you the important bits you need to know.

Descendant Selectors

In the last lesson, we took a look at selectors in CSS. Here, I’ll introduce another form of CSS selectors.

Let’s see an example.

Consider the basic html markup below:

Press + to interact
<html>
<head></head>
<title>Descendant selectors</title>
<body>
<div>
<h1>DIV: Header 1</h1>
<h2>DIV: Header 2</h2>
</div>
<section>
<h1>Header 1</h1>
<h2>Header 2</h2>
</section>
</body>
</html>

The markup above is fairly simple. The important bit is between line 5 and 12.

You’d notice that the div on line 5 houses two header elements h1 and h2. The same may be said of the section on line 9.

Generally, the html DOM can be represented in terms of parent-child relationship. What I mean by that is, since the div on line 5 houses the h1 and h2 elements, the div may be called their parent element. Consequently, the header elements, h1 and h2 may be referred to as child elements.

CSS avails us a way to select elements based off of their DOM relationship. A pivotal one is the descendant selector - which is based on parent and child relationship.

Let’s see an example.

In the markup discussed above, how do you select the h1 and h2 within the div only?

Using descendant selectors, do this:

Press + to interact
div h1 {
color: red;
}
div h2 {
color: red;
}

The CSS above will ONLY select the h1 and h2 within the div. The other h1 and h2 within the section tag will be left unstyled.

widget

As you can see above, the headers within the section are left unstyled. Header 1 and Header 2 are left unstyled! Interesting.

Now go ahead and style the header elements within the section.

Here’s my solution:

Press + to interact
section h1,
section h2 {
color: blue;
}

You see what ...