Getting Started with CSS Rules

Styling things based on their location in a document

There are times when you will want something to look different based on where it is in the document. There are a number of selectors that can help you here, but for now we will look at just a couple. In our document, there are two <em> elements – one inside a paragraph and the other inside a list item. To select only an <em> that is nested inside an <li> element I can use a selector called the descendant combinator, which takes the form of a space between two other selectors.

Add the following rule to your stylesheet.

li em {
  color: rebeccapurple;
}

This selector will select any <em> element that is inside (a descendant of) an <li>. So in your example document, you should find that the <em> in the third list item is now purple, but the one inside the paragraph is unchanged.

Something else you might like to try is styling a paragraph when it comes directly after a heading at the same hierarchy level in the HTML. To do so place a + (an adjacent sibling combinator) between the selectors.

Try adding this rule to your stylesheet as well:

h1 + p {
  font-size: 200%;
}

Try adding a rule to make a span red, if it is inside a paragraph. You will know if you have it right as the span in the first paragraph will be red, but the one in the first list item will not change color.

I am a level one heading

This is a paragraph of text. In the text is a span element and also a link.

This is the second paragraph. It contains an emphasized element.

  • Item one
  • Item two
  • Item three


CSS and HTML
li em {
    color: rebeccapurple;
}

h1 + p {
    font-size: 200%;
}

<h1>I am a level one heading</h1>

<p>This is a paragraph of text. In the text is a <span>span element</span>
and also a <a href="http://example.com">link</a>.</p>

<p>This is the second
    paragraph. It contains an <em>emphasized</em> element.</p>

<ul>
    <li>Item <span>one</span></li>
    <li>Item two</li>
    <li>Item
    <em>three</em></li>
</ul>

Note: As you can see, CSS gives us several ways to target elements, and we've only scratched the surface so far! We will be taking a proper look at all of these selectors and many more in our Selectors articles later on in the course.