Using id in CSS

When using id, all the selector manipulations we learned in previous lessons are available.

Example

Let's say we have the following code:

html<div id="block">
  <h2>Title</h2>
  <p>text</p>
  <p>text</p>
</div>

Let's select h2 from the element with id equal to block and color it red:

css#block h2 {
  color: red;
}

Now let's select p from the element with id equal to block and color it green:

css#block p {
  color: green;
}

Example

Let's now assume we have the following code:

html<div id="block">
  <h2 class="header">Title</h2>
  <p>text</p>
  <p>text</p>
  
  <h3 class="header">Title</h3>
  <p>text</p>
  <p>text</p>
</div>

Let's select elements with class header that are inside an element with id equal to block and color them red:

css#block .header {
  color: red;
}

Now let's select the h2 headings with the class header, inside the element with id equal to block, and color them red:

css#block h2.header {
  color: red;
}

Practical tasks

Задание 1

Write a selector that selects all h2 that are in an element with id equal to elem. Test your selector on the following code:

html<div id="elem">
  <h2>Choose</h2>
  <p>---</p>
  
  <h2>Choose</h2>
  <p>---</p>
</div>

<h2>Do not +++</h2>
<p>---</p>
Задание 2

Write a selector that selects all elements with class text that are contained within an element with id equal to elem. Test your selector against the following code:

html<div id="elem">
  <p class="text">+++</p>
  <p class="text">+++</p>
  
  <ul>
    <li class="text">+++</li>
    <li class="text">+++</li>
    <li class="text">+++</li>
    <li>---</li>
    <li>---</li>
  </ul>
</div>

<p class="text">---</p>
Задание 3

Write a selector that selects all paragraphs with class text that are contained within an element with id equal to elem. Test your selector against the following code:

html<div id="elem">
  <p class="text">+++</p>
  <p class="text">+++</p>
  
  <ul>
    <li class="text">---</li>
    <li class="text">---</li>
    <li class="text">---</li>
    <li>---</li>
    <li>---</li>
  </ul>
</div>

<p class="text">---</p>
Задание 4

Write a selector that selects all li with class text that are on an element with id equal to elem. Test your selector on the following code:

html<div id="elem">
  <p class="text">---</p>
  <p class="text">---</p>
  
  <ul>
    <li class="text">+++</li>
    <li class="text">+++</li>
    <li class="text">+++</li>
    <li>---</li>
    <li>---</li>
  </ul>
</div>

<p class="text">---</p>