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:
<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:
#block h2 {
color: red;
}
Now let's select p from the element with id equal to block and color it green:
#block p {
color: green;
}
Example
Let's now assume we have the following code:
<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:
#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:
#block h2.header {
color: red;
}
Practical tasks
Write a selector that selects all h2 that are in an element with id equal to elem. Test your selector on the following code:
<div id="elem">
<h2>Choose</h2>
<p>---</p>
<h2>Choose</h2>
<p>---</p>
</div>
<h2>Do not +++</h2>
<p>---</p>
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:
<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>
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:
<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>
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:
<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>