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 1108501 of Attribute selectors

  • Revision slug: Learn/CSS/Introduction_to_CSS/Attribute_selectors
  • Revision title: Attribute selectors
  • Revision id: 1108501
  • Created:
  • Creator: chrisdavidmills
  • Is current revision? No
  • Comment Learn/CSS/Introduction_to_CSS/Selectors/Attribute_selectors Learn/CSS/Introduction_to_CSS/Attribute_selectors

Revision Content

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

Attribute selectors are a special kind of selector that will match elements based on their {{Glossary("attribute", "attributes")}} and attribute values. Their generic syntax consists of square brackets ([]) containing an attribute name followed by an optional condition to match against the value of the attribute. Attribute selectors can be divided into two categories depending on the way they match attribute values: Presence and value attribute selectors and Substring value attribute selectors.

Presence and value attribute selectors

These attribute selectors try to match an exact attribute value:

  • [attr] : This selector will select all elements with the attribute attr, whatever its value.
  • [attr=val] : This selector will select all elements with the attribute attr, but only if its value is val.
  • [attr~=val]: This selector will select all elements with the attribute attr, but only if the value val is one of a space-separated list of values contained in attr's value, for example a single class in a space-separated list of classes.

Let's look at an example featuring the following HTML snippet:

Ingredients for my recipe: <i lang="fr-FR">Poulet basquaise</i>
<ul>
  <li data-quantity="1kg" data-vegetable>Tomatoes</li>
  <li data-quantity="3" data-vegetable>Onions</li>
  <li data-quantity="3" data-vegetable>Garlic</li>
  <li data-quantity="700g" data-vegetable="not spicy like chili">Red pepper</li>
  <li data-quantity="2kg" data-meat>Chicken</li>
  <li data-quantity="optional 150g" data-meat>Bacon bits</li>
  <li data-quantity="optional 10ml" data-vegetable="liquid">Olive oil</li>
  <li data-quantity="25cl" data-vegetable="liquid">White wine</li>
</ul>

And a simple style sheet:

/* All elements with the attribute "data-vegetable"
   are given green text */
[data-vegetable] {
  color: green
}

/* All elements with the attribute "data-vegetable"
   with the exact value "liquid" are given a golden
   background color */
[data-vegetable="liquid"] {
  background-color: goldenrod;
}

/* All elements with the attribute "data-vegetable",
   containing the value "spicy", even among others,
   are given a red background color */
[data-vegetable~="spicy"] {
  color: red;
}

The result is as follows:

{{ EmbedLiveSample('Presence_and_value_attribute_selectors', '100%', '208px') }}

Substring value attribute selectors

Attribute selectors in this class are also known as "RegExp-like selectors", because they offer flexible matching in a similar fashion to {{Glossary("regular expression")}} (but to be clear, these selectors are not true regular expression):

  • [attr|=val] : This selector will select all elements with the attribute attr for which the value is exactly val or starts with val- (careful, the dash here isn't a mistake, this is to handle language codes.)
  • [attr^=val] : This selector will select all elements with the attribute attr for which the value starts with val.
  • [attr$=val] : This selector will select all elements with the attribute attr for which the value ends with val.
  • [attr*=val] : This selector will select all elements with the attribute attr for which the value contains the string val (unlike [attr~=val], this selector doesn't treat spaces as value separators but as part of the attribute value.)

Let's continue our previous example and add the following CSS rules:

/* Classic usage for language selection */
[lang|=fr] {
  font-weight: bold;
}

/* All elements with the attribute "data-vegetable" containing
   the value "not spicy" are turned back to green */
[data-vegetable*="not spicy"] {
  color: green;
}

/* All elements with the attribute "data-quantity", for which
   the value ends with "kg" */
[data-quantity$="kg"] {
  font-weight: bold;
}

/* All elements with the attribute "data-quantity", for which the
   value starts with "optional" */
[data-quantity^="optional"] {
  opacity: 0.5;
}

 

With those new rules, we will get this:

{{ EmbedLiveSample('Substring_value_attribute_selectors', '100%', '208px') }}

Active learning: Styling football results

In this active learning, we'd like you to try your hand at adding attribute selectors to some rules to style a simple football results listing. There are three things to try to do here:

  • The first three rules add a UK, German, and Spanish flag icon respectively to the left hand side of the list items. You need to fill in appropriate attribute selectors so that the teams are given their correct country flags, matched by language.
  • Rules 4–6 add a background color to the list items to indicate whether the team has gone up in the league (green, rgba(0,255,0,0.7)), down (red, rgba(255,0,0,0.5)), or stayed in the same place (blue, rgba(0,0,255,0.5).)  Fill in the appropriate attribute selectors to match the correct colors to the correct teams, matched by the inc, same and dec strings that appear in the data-perf attribute values.
  • Rules 7–8 make teams that are set to be promoted bold, and teams that are in danger of being relegated italic and gray. Fill in appropriate attribute selectors to match these styles to the correct teams, matched by the pro and rel strings that appear in the data-perf attribute values.

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_4', 700, 800) }}

Coming up next

Next we will move things up a gear, looking at Pseudo-classes and pseudo-elements.

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

Revision Source

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

<p class="summary">Attribute selectors are a special kind of selector&nbsp;that will match elements based on their {{Glossary("attribute", "attributes")}} and attribute values. Their generic syntax consists of square brackets (<code>[]</code>) containing an attribute name followed by an optional condition to match against the value of the attribute. Attribute selectors can be divided into two categories depending on the way they match attribute values: <strong>Presence and value</strong> attribute selectors and <strong>Substring value</strong> attribute selectors.</p>

<h2 id="Presence_and_value_attribute_selectors">Presence and value attribute selectors</h2>

<p>These attribute selectors try to match an exact attribute value:</p>

<ul>
 <li><code>[attr]</code> : This selector will select all elements with the attribute <code>attr</code>, whatever its value.</li>
 <li><code>[attr=val]</code> : This selector will select all elements with the attribute <code>attr</code>, but only if its value is <code>val</code>.</li>
 <li><code>[attr~=val]</code>: This selector will select all elements with the attribute <code>attr</code>, but only if the value <code>val</code> is one of a space-separated list of values contained in <code>attr</code>'s value, for example a single class in a space-separated list of classes.</li>
</ul>

<p>Let's look at an example featuring the following HTML snippet:</p>

<pre class="brush: html">
Ingredients for my recipe: &lt;i lang="fr-FR"&gt;Poulet basquaise&lt;/i&gt;
&lt;ul&gt;
  &lt;li data-quantity="1kg" data-vegetable&gt;Tomatoes&lt;/li&gt;
  &lt;li data-quantity="3" data-vegetable&gt;Onions&lt;/li&gt;
  &lt;li data-quantity="3" data-vegetable&gt;Garlic&lt;/li&gt;
  &lt;li data-quantity="700g" data-vegetable="not spicy like chili"&gt;Red pepper&lt;/li&gt;
  &lt;li data-quantity="2kg" data-meat&gt;Chicken&lt;/li&gt;
  &lt;li data-quantity="optional 150g" data-meat&gt;Bacon bits&lt;/li&gt;
  &lt;li data-quantity="optional 10ml" data-vegetable="liquid"&gt;Olive oil&lt;/li&gt;
  &lt;li data-quantity="25cl" data-vegetable="liquid"&gt;White wine&lt;/li&gt;
&lt;/ul&gt;</pre>

<p>And a simple style sheet:</p>

<pre class="brush: css">
/* All elements with the attribute "data-vegetable"
   are given green text */
[data-vegetable] {
  color: green
}

/* All elements with the attribute "data-vegetable"
   with the exact value "liquid" are given a golden
   background color */
[data-vegetable="liquid"] {
  background-color: goldenrod;
}

/* All elements with the attribute "data-vegetable",
   containing the value "spicy", even among others,
   are given a red background color */
[data-vegetable~="spicy"] {
  color: red;
}
</pre>

<p>The result is as follows:</p>

<p>{{ EmbedLiveSample('Presence_and_value_attribute_selectors', '100%', '208px') }}</p>

<h2 id="Substring_value_attribute_selectors">Substring value attribute selectors</h2>

<p>Attribute selectors in this class are also known as "RegExp-like selectors", because they offer flexible matching in a similar fashion to {{Glossary("regular expression")}} (but to be clear, these selectors are not true regular expression):</p>

<ul>
 <li><code>[attr|=val]</code> : This selector will select all elements with the attribute <code>attr</code> for which the value is exactly <code>val</code> or starts with <code>val-</code> (careful, the dash here isn't a mistake, this is to handle language codes.)</li>
 <li><code>[attr^=val]</code> : This selector will select all elements with the attribute <code>attr</code> for which the value starts with <code>val</code>.</li>
 <li><code>[attr$=val]</code> : This selector will select all elements with the attribute <code>attr</code> for which the value ends with <code>val</code>.</li>
 <li><code>[attr*=val]</code> : This selector will select all elements with the attribute <code>attr</code> for which the value contains the string <code>val</code> (unlike <code>[attr~=val]</code>, this selector doesn't treat spaces as value separators but as part of the attribute value.)</li>
</ul>

<p>Let's continue our previous example and add the following CSS rules:</p>

<div class="hidden">
<pre class="brush: html">
Ingredients for my recipe: &lt;i lang="fr-FR"&gt;Poulet basquaise&lt;/i&gt;
&lt;ul&gt;
  &lt;li data-quantity="1kg" data-vegetable&gt;Tomatoes&lt;/li&gt;
  &lt;li data-quantity="3" data-vegetable&gt;Onions&lt;/li&gt;
  &lt;li data-quantity="3" data-vegetable&gt;Garlic&lt;/li&gt;
  &lt;li data-quantity="700g" data-vegetable="not spicy like chili"&gt;Red pepper&lt;/li&gt;
  &lt;li data-quantity="2kg" data-meat&gt;Chicken&lt;/li&gt;
  &lt;li data-quantity="optional 150g" data-meat&gt;Bacon bits&lt;/li&gt;
  &lt;li data-quantity="optional 10ml" data-vegetable="liquid"&gt;Olive oil&lt;/li&gt;
  &lt;li data-quantity="25cl" data-vegetable="liquid"&gt;White wine&lt;/li&gt;
&lt;/ul&gt;</pre>
</div>

<pre class="brush: css">
/* Classic usage for language selection */
[lang|=fr] {
  font-weight: bold;
}

/* All elements with the attribute "data-vegetable" containing
   the value "not spicy" are turned back to green */
[data-vegetable*="not spicy"] {
  color: green;
}

/* All elements with the attribute "data-quantity", for which
   the value ends with "kg" */
[data-quantity$="kg"] {
  font-weight: bold;
}

/* All elements with the attribute "data-quantity", for which the
   value starts with "optional" */
[data-quantity^="optional"] {
  opacity: 0.5;
}</pre>

<div class="hidden">/* All elements with the attribute "data-vegetable" are given green text */ [data-vegetable] { color: green } /* All elements with the attribute "data-vegetable" with the exact value "liquid" are given a golden background color */ [data-vegetable="liquid"] { background-color: goldenrod; } /* All elements with the attribute "data-vegetable", containing the value "spicy", even among others, are given a red background color */ [data-vegetable~="spicy"] { color: red; }</div>

<p>&nbsp;</p>

<p>With those new rules, we will get this:</p>

<p>{{ EmbedLiveSample('Substring_value_attribute_selectors', '100%', '208px') }}</p>

<h2 id="Active_learning_Styling_football_results">Active learning: Styling football results</h2>

<p>In this active learning, we'd like you to try your hand at adding attribute selectors to some rules to style a simple football results listing. There are three things to try to do here:</p>

<ul>
 <li>The first three rules add a UK, German, and Spanish flag icon respectively to the left hand side of the list items. You need to fill in appropriate attribute selectors so that the teams are given their correct country flags, matched by language.</li>
 <li>Rules 4–6 add a background color to the list items to indicate whether the team has gone up in the league (green, <code>rgba(0,255,0,0.7)</code>), down (red, <code>rgba(255,0,0,0.5)</code>), or stayed in the same place (blue, <code>rgba(0,0,255,0.5)</code>.)&nbsp; Fill in the appropriate attribute selectors to match the correct colors to the correct teams, matched by the <code>inc</code>, <code>same</code> and <code>dec</code> strings that appear in the <code>data-perf</code> attribute values.</li>
 <li>Rules 7–8 make teams that are set to be promoted <strong>bold</strong>, and teams that are in danger of being relegated <em style="color:#666">italic and gray</em>. Fill in appropriate attribute selectors to match these styles to the correct teams, matched by the <code>pro</code> and <code>rel</code> strings that appear in the <code>data-perf</code> attribute values.</li>
</ul>

<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_4">Playable code 4</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;ol&gt;
  &lt;li lang="en-GB" data-perf="inc-pro"&gt;Manchester United&lt;/li&gt;
  &lt;li lang="es" data-perf="same-pro"&gt;Barcelona&lt;/li&gt;
  &lt;li lang="de" data-perf="dec"&gt;Bayern Munich&lt;/li&gt;
  &lt;li lang="es" data-perf="same"&gt;Real Madrid&lt;/li&gt;
  &lt;li lang="de" data-perf="inc-rel"&gt;Borussia Dortmund&lt;/li&gt;
  &lt;li lang="en-GB" data-perf="dec-rel"&gt;Southampton FC&lt;/li&gt;
&lt;/ol&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;li[] {
 &nbsp; background: url("https://mdn.github.io/learning-area/css/introduction-to-css/css-selectors/en-GB.png") 5px center no-repeat;
 }

li[] {
 &nbsp; background: url("https://mdn.github.io/learning-area/css/introduction-to-css/css-selectors/de.png") 5px center no-repeat;
 }

li[] {
 &nbsp; background: url("https://mdn.github.io/learning-area/css/introduction-to-css/css-selectors/es.png") 5px center no-repeat;
 }

li[] {
 &nbsp; background-color: rgba(0,255,0,0.7);
 }

li[] {
 &nbsp; background-color: rgba(0,0,255,0.5);
 }

li[] {
 &nbsp; background-color: rgba(255,0,0,0.7);
 }

li[] {
 &nbsp; font-weight: bold;
 }

li[] {
 &nbsp; font-style: italic;
 &nbsp; color: #666;
 }

ol {
 &nbsp; padding: 0;
 }

li {
 &nbsp; padding: 3px 3px 3px 34px;
 &nbsp; margin-bottom: 5px;
 &nbsp; list-style-position: inside;
 }&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 = 'li[lang="en-GB"] {\n &nbsp; background: url("https://mdn.github.io/learning-area/css/introduction-to-css/css-selectors/en-GB.png") 5px center no-repeat;\n}\n\nli[lang="de"] {\n &nbsp; background: url("https://mdn.github.io/learning-area/css/introduction-to-css/css-selectors/de.png") 5px center no-repeat;\n}\n\nli[lang="es"] {\n &nbsp; background: url("https://mdn.github.io/learning-area/css/introduction-to-css/css-selectors/es.png") 5px center no-repeat;\n}\n\nli[data-perf*="inc"] {\n &nbsp; background-color: rgba(0,255,0,0.7);\n}\n\nli[data-perf*="same"] {\n &nbsp; background-color: rgba(0,0,255,0.5);\n}\n\nli[data-perf*="dec"] {\n &nbsp; background-color: rgba(255,0,0,0.7);\n}\n\nli[data-perf*="pro"] {\n &nbsp; font-weight: bold;\n}\n\nli[data-perf*="rel"] {\n &nbsp; font-style: italic;\n &nbsp; color: #666;\n}\n\nol {\n &nbsp; padding: 0;\n}\n\nli {\n &nbsp; padding: 3px 3px 3px 34px;\n &nbsp; margin-bottom: 5px;\n &nbsp; list-style-position: inside;\n}';
  drawOutput();
});

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

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

<h2 id="Coming_up_next">Coming up next</h2>

<p>Next we will move things up a gear, looking at <a href="/en-US/docs/Learn/CSS/Introduction_to_CSS/Selectors/Pseudo-classes_and_pseudo-elements">Pseudo-classes and pseudo-elements</a>.</p>

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