Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1108511 of Combinators and multiple selectors

  • Revision slug: Learn/CSS/Introduction_to_CSS/Combinators_and_multiple_selectors
  • Revision title: Combinators and multiple selectors
  • Revision id: 1108511
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment

Revision Content

{{PreviousMenuNext("Learn/CSS/Introduction_to_CSS/Pseudo-classes_and_pseudo-elements","Learn/CSS/Introduction_to_CSS/Values_and_units", "Learn/CSS/Introduction_to_CSS")}}

In our final article on selectors we'll explore combinators and multiple selectors — two ways of combining multiple selectors together for further useful selection capabilities.

Combinators

Using one selector at a time is useful, but can be inefficient in some situations. CSS selectors become even more useful when you start combining them to perform fine-grained selections. CSS has several ways to select elements based on how they are related to one another. Those relationships are expressed with combinators as follows (A and B represent any selector seen above):

Combinators Select
AB Any element matching both A and B at the same time.
A B Any element matching B that is a descendant of an element matching A (that is: a child, or a child of a child, etc.)
A > B Any element matching B that is a direct child of an element matching A.
A + B Any element matching B that is the next sibling of an element matching A (that is: the next child of the same parent.)
A ~ B Any element matching B that is among the next sibling of an element matching A (that is: one of the next children of the same parent.)

Combinators example

Let's look at an example with all of this working together:

<table lang="en-US" class="with-currency">
  <thead>
    <tr>
      <th scope="col">Product</th>
      <th scope="col">Qty.</th>
      <th scope="col">Price</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th colspan="2" scope="row">Total:</th>
      <td>148.55</td>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>Lawnchair</td>
      <td>1</td>
      <td>137.00</td>
    </tr>
    <tr>
      <td>Marshmallow rice bar</td>
      <td>2</td>
      <td>1.10</td>
    </tr>
    <tr>
      <td>Book</td>
      <td>1</td>
      <td>10.45</td>
    </tr>
  </tbody>
</table>

Then let's use the following style sheet:

/* Basic table setup */
table {
  font: 1em sans-serif;
  border-collapse: collapse;
  border-spacing: 0;
}

/* All <td>s within a <table and all <th>s within a <table>
   Comma is not a combinator, it just allows you to target
   several selectors with the same CSS ruleset */
table td, table th {
  border : 1px solid black;
  padding: 0.5em 0.5em 0.4em;
}

/* All <th>s within <thead>s that are within <table>s */
table thead th {
  color: white;
  background: black;
}

/* All <td>s preceded by another <td>,
   within a <tbody>, within a <table> */
table tbody td + td {
  text-align: center;
}

/* All <td>s that are a last child,
   within a <tbody>, within a <table> */
table tbody td:last-child {
  text-align: right
}

/* All <th>s, within a <tfoot>s, within a <table> */
table tfoot th {
  text-align: right;
  border-top-width: 5px;
  border-left: none;
  border-bottom: none;
}

/* All <td>s preceded by a <th>, within a <table> */
table th + td {
  text-align: right;
  border-top-width: 5px;
  color: white;
  background: black;
}

/* All pseudo-elements "before" <td>s that are a last child,
   appearing within elements with a class of "with-currency" that
   also have an attribute "lang" with the value "en-US" */
.with-currency[lang="en-US"] td:last-child::before {
  content: '$';
}

/* All pseudo-elements "after" <td>s that are a last child,
   appearing within elements with the class "with-currency" that
   also have an attribute "lang" with the value "fr" */
.with-currency[lang="fr"] td:last-child::after {
  content: ' €';
}

This has given us the following rather nice table styles:

{{ EmbedLiveSample('Combinators_example', '100%', '176px') }}

Active learning: Writing your own combinators

The above example was designed to show the sort of complexity you can start to achieve with combinators. In this active learning, we will get you to write some of your own, more simple selectors that include combinators. In this exercise you need to add a selector to rules 2–4, to:

  1. Style links, but only links that are inside the unordered list.
  2. Style links inside the unordered list, only when they are being hovered over.
  3. Style only the paragraph that comes directly after the top level heading.

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see a potential answer.

{{ EmbedLiveSample('Playable_code_7', 700, 800) }}

Multiple selectors on one rule

You have seen multiple examples of this in action already, but let's spell it out clearly for clarification. You can write multiple selectors separated by commas, to apply the same rule to multiple sets of selected elements at once. For example:

p, li {
  font-size: 1.6em;
}

Or this:

 h1, h2, h3, h4, h5, h6 {
  font-family: helvetica, 'sans serif';
}

What's next

Congratulations, you've come to the end of our rather long journey into learning about Selectors. Even the most skilled web developers are still amazed by what's possible using selectors — don't feel bad if you can't remember all the options — bookmark the main selectors page and refer back to it when you need to.

In our next article we'll turn to another really important fundamental CSS topic — the kinds of values properties can have, and what units are involved in expressing the length, color, or other values you want.  Let's explore CSS values and units.

{{PreviousMenuNext("Learn/CSS/Introduction_to_CSS/Selectors/Pseudo-classes_and_pseudo-elements","Learn/CSS/Introduction_to_CSS/Values_and_units", "Learn/CSS/Introduction_to_CSS/Selectors")}}

Revision Source

<p>{{PreviousMenuNext("Learn/CSS/Introduction_to_CSS/Pseudo-classes_and_pseudo-elements","Learn/CSS/Introduction_to_CSS/Values_and_units", "Learn/CSS/Introduction_to_CSS")}}</p>

<p class="summary">In our final article on selectors we'll explore combinators and multiple selectors — two ways of combining multiple selectors together for further useful selection capabilities.</p>

<h2 id="Combinators">Combinators</h2>

<p>Using one selector at a time is useful, but can be inefficient in some situations. CSS selectors become even more useful when you start combining them to perform fine-grained selections. CSS has several ways to select elements based on how they are related to one another. Those relationships are expressed with <em>combinators</em> as follows (A and B represent any selector seen above):</p>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Combinators</th>
   <th scope="col">Select</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>AB</td>
   <td>Any element matching both A and B at the same time.</td>
  </tr>
  <tr>
   <td>A B</td>
   <td>Any element matching B that is a <em>descendant</em> of an element matching A (that is: a child, or a child of a child, <em>etc</em>.)</td>
  </tr>
  <tr>
   <td>A &gt; B</td>
   <td>Any element matching B that is a <em>direct child</em> of an element matching A.</td>
  </tr>
  <tr>
   <td>A + B</td>
   <td>Any element matching B that is the next <em>sibling</em> of an element matching A (that is: the next child of the same parent.)</td>
  </tr>
  <tr>
   <td>A ~ B</td>
   <td>Any element matching B that is among the next <em>sibling</em> of an element matching A (that is: one of the next children of the same parent.)</td>
  </tr>
 </tbody>
</table>

<h3 id="Combinators_example">Combinators example</h3>

<p>Let's look at&nbsp;an example with all of this working together:</p>

<pre class="brush: html">
&lt;table lang="en-US" class="with-currency"&gt;
  &lt;thead&gt;
    &lt;tr&gt;
      &lt;th scope="col"&gt;Product&lt;/th&gt;
      &lt;th scope="col"&gt;Qty.&lt;/th&gt;
      &lt;th scope="col"&gt;Price&lt;/th&gt;
    &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tfoot&gt;
    &lt;tr&gt;
      &lt;th colspan="2" scope="row"&gt;Total:&lt;/th&gt;
      &lt;td&gt;148.55&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tfoot&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;Lawnchair&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;137.00&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Marshmallow rice bar&lt;/td&gt;
      &lt;td&gt;2&lt;/td&gt;
      &lt;td&gt;1.10&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;Book&lt;/td&gt;
      &lt;td&gt;1&lt;/td&gt;
      &lt;td&gt;10.45&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;
&lt;/table&gt;</pre>

<p>Then let's use the following style sheet:</p>

<pre class="brush: css">
/* Basic table setup */
table {
  font: 1em sans-serif;
  border-collapse: collapse;
  border-spacing: 0;
}

/* All &lt;td&gt;s within a &lt;table and all &lt;th&gt;s within a &lt;table&gt;
   Comma is not a combinator, it just allows you to target
   several selectors with the same CSS ruleset */
table td, table th {
  border : 1px solid black;
  padding: 0.5em 0.5em 0.4em;
}

/* All &lt;th&gt;s within &lt;thead&gt;s that are within &lt;table&gt;s */
table thead th {
  color: white;
  background: black;
}

/* All &lt;td&gt;s preceded by another &lt;td&gt;,
   within a &lt;tbody&gt;, within a &lt;table&gt; */
table tbody td + td {
  text-align: center;
}

/* All &lt;td&gt;s that are a last child,
   within a &lt;tbody&gt;, within a &lt;table&gt; */
table tbody td:last-child {
  text-align: right
}

/* All &lt;th&gt;s, within a &lt;tfoot&gt;s, within a &lt;table&gt; */
table tfoot th {
  text-align: right;
  border-top-width: 5px;
  border-left: none;
  border-bottom: none;
}

/* All &lt;td&gt;s preceded by a &lt;th&gt;, within a &lt;table&gt; */
table th + td {
  text-align: right;
  border-top-width: 5px;
  color: white;
  background: black;
}

/* All pseudo-elements "before" &lt;td&gt;s that are a last child,
   appearing within elements with a class of "with-currency" that
   also have an attribute "lang" with the value "en-US" */
.with-currency[lang="en-US"] td:last-child::before {
  content: '$';
}

/* All pseudo-elements "after" &lt;td&gt;s that are a last child,
   appearing within elements with the class "with-currency" that
   also have an attribute "lang" with the value "fr" */
.with-currency[lang="fr"] td:last-child::after {
  content: ' €';
}
</pre>

<p>This has given us the following rather nice table styles:</p>

<p>{{ EmbedLiveSample('Combinators_example', '100%', '176px') }}</p>

<h3 id="Active_learning_Writing_your_own_combinators">Active learning: Writing your own combinators</h3>

<p>The above example was designed to show the sort of complexity you can start to achieve with combinators. In this active learning, we will get you to write some of your own, more simple selectors that include combinators. In this exercise you need to add a selector to rules 2–4, to:</p>

<ol>
 <li>Style links, but only links that are inside the unordered list.</li>
 <li>Style links inside the unordered list, only when they are being hovered over.</li>
 <li>Style only the paragraph that comes directly after the top level heading.</li>
</ol>

<p>If you make a mistake, you can always reset it using the <em>Reset</em> button. If you get really stuck, press the <em>Show solution</em> button to see a potential answer.</p>

<div class="hidden">
<h6 id="Playable_code_7">Playable code 7</h6>

<pre class="brush: html">
&lt;div class="body-wrapper" style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;"&gt;
  &lt;h2&gt;HTML Input&lt;/h2&gt;
  &lt;textarea id="code" class="html-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"&gt;&lt;ul&gt;
  &lt;li&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/li&gt;
  &lt;li&gt;&lt;a href="#"&gt;Portfolio&lt;/a&gt;&lt;/li&gt;  
  &lt;li&gt;&lt;a href="#"&gt;About&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h1&gt;Welcome to my website&lt;/h1&gt;

&lt;p&gt;Hello, and welcome! I hope you enjoy your time here.&lt;/p&gt;

&lt;h2&gt;My philosophy&lt;/h2&gt;

&lt;p&gt;I am a believer in chilling out, and not getting grumpy. I think everyone else should follow this ideal, and &lt;a href="#"&gt;drink green tea&lt;/a&gt;.&lt;/p&gt;&lt;/textarea&gt;

  &lt;h2&gt;CSS Input&lt;/h2&gt;
  &lt;textarea id="code" class="css-input" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"&gt;ul {
  padding: 0;
  list-style-type: none;
}

 {
  text-decoration: none;
  display: block;
  color: black;
  background-color: red;
  padding: 5px;
  margin-bottom: 10px;
}

 {
  color: red;
  background-color: black;
}

 {
  font-style: bold;
  color: blue;
}&lt;/textarea&gt;

  &lt;h2&gt;Output&lt;/h2&gt;
  &lt;div class="output" style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;overflow:auto;"&gt;&lt;/div&gt;
  &lt;div class="controls"&gt;
&nbsp;   &lt;input id="reset" type="button" value="Reset" style="margin: 10px 10px 0 0;"&gt;
    &lt;input id="solution" type="button" value="Show solution" style="margin: 10px 0 0 10px;"&gt;
  &lt;/div&gt;
&lt;/div&gt;
</pre>

<pre class="brush: js">
var htmlInput = document.querySelector(".html-input");
var cssInput = document.querySelector(".css-input");
var reset = document.getElementById("reset");
var htmlCode = htmlInput.value;
var cssCode = cssInput.value;
var output = document.querySelector(".output");
var solution = document.getElementById("solution");

var styleElem = document.createElement('style');
var headElem = document.querySelector('head');
headElem.appendChild(styleElem);

function drawOutput() {
  output.innerHTML = htmlInput.value;
  styleElem.textContent = cssInput.value;
}

reset.addEventListener("click", function() {
&nbsp; htmlInput.value = htmlCode;
&nbsp; cssInput.value = cssCode;
&nbsp; drawOutput();
});

solution.addEventListener("click", function() {
  htmlInput.value = htmlCode;
  cssInput.value = 'ul {\n  padding: 0;\n  list-style-type: none;\n}\n\nul a {\n  text-decoration: none;\n  display: block;\n  color: black;\n  background-color: red;\n  padding: 5px;\n  margin-bottom: 10px;\n}\n\nul a:hover {\n  color: red;\n  background-color: black;\n}\n\nh1 + p {\n  font-style: bold;\n  color: blue;\n}';
  drawOutput();
});

htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);
</pre>
</div>

<p>{{ EmbedLiveSample('Playable_code_7', 700, 800) }}</p>

<h2 id="Multiple_selectors_on_one_rule">Multiple selectors on one rule</h2>

<p>You have seen multiple examples of this in action already, but let's spell it out clearly for clarification. You can write multiple selectors separated by commas, to apply the same&nbsp;rule to multiple sets of selected elements at once. For example:</p>

<pre class="brush: css">
p, li {
  font-size: 1.6em;
}</pre>

<p>Or this:</p>

<pre class="brush: css">
 h1, h2, h3, h4, h5, h6 {
  font-family: helvetica, 'sans serif';
}</pre>

<h2 id="What's_next">What's next</h2>

<p>Congratulations, you've come to the end of our rather long journey into learning about Selectors. Even the most skilled web developers are still amazed by what's possible using selectors — don't feel bad if you can't remember all the options — bookmark the main <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors">selectors page</a> and refer back to it when you need to.</p>

<p>In our next article we'll turn to another really important fundamental CSS topic — the kinds of values properties can have, and what units are involved in expressing the length, color, or other values you want.&nbsp; Let's explore <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Values_and_units">CSS values and units</a>.</p>

<p>{{PreviousMenuNext("Learn/CSS/Introduction_to_CSS/Selectors/Pseudo-classes_and_pseudo-elements","Learn/CSS/Introduction_to_CSS/Values_and_units", "Learn/CSS/Introduction_to_CSS/Selectors")}}</p>
Revert to this revision