CSS attribute selectors

Lecture



Many tags differ in their action depending on which attributes are used in them. For example, the <input> tag can create a button, a text field, and other form elements just by changing the value of the type attribute. At the same time, adding style rules to the INPUT selector will apply the style simultaneously to all elements created using this tag. To flexibly control the style of similar elements, attribute selectors are introduced in CSS. They allow you to set the style according to the presence of a specific attribute of the tag or its value.

Consider a few typical applications of such selectors.

Simple attribute selector

Sets the style for an element if a specific tag attribute is specified. Its meaning is not important in this case. The syntax for using such a selector is as follows.

[attribute] {Description of style rules}
Selector [attribute] {Description of style rules}

The style is applied to the tags within which the specified attribute is added. The space between the selector name and the square brackets is not allowed.

Example 13.1 shows a change in the style of the <q> tag, if the title attribute is added to it.

Example 13.1. Type of element depending on its attribute

HTML5CSS 2.1IECrOpSaFx

<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Селекторы атрибутов</title> <style> Q { font-style: italic; /* Курсивное начертание */ quotes: "\00AB" "\00BB"; /* Меняем вид кавычек в цитате */ } Q[title] { color: maroon; /* Цвет текста */ } </style> </head> <body> <p>Продолжая известный закон Мерфи, который гласит: <q>Если неприятность может случиться, то она обязательно случится</q>, можем ввести свое наблюдение: <q title="Из законов Фергюссона-Мержевича">После того, как веб-страница будет корректно отображаться в одном браузере, выяснится, что она неправильно показывается в другом</q>.</p> </body> </html> 


The result of the example is shown in Fig. 13.1.

  CSS attribute selectors

Fig. 13.1. Change the style of the element depending on the use of the title attribute

In this example, the text color inside the <q> container changes when the title is added to it. Note that for the Q [title] selector there is no need to repeat the style properties, since they are inherited from the Q selector.

Attribute with value

Sets the style for an element if a specific attribute value is specified. The syntax is as follows.

[attribute = "value"] {Description of style rules}
Selector [attribute = "value"] {Description of style rules}

In the first case, the style is applied to all tags that contain the specified value. And in the second - only to certain selectors.

Example 13.2 shows the link style change if the <a> tag contains a target attribute with the value of_blank. In this case, the link will open in a new window and to show this, with the help of styles, add a small picture in front of the link text.

Example 13.2. Style for opening links in a new window.

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Селекторы атрибутов</title> <style> A[target="_blank"] { background: url(images/blank.png) 0 6px no-repeat; /* Параметры фонового рисунка */ padding-left: 15px; /* Смещаем текст вправо */ } </style> </head> <body> <p><a href="1.html">Обычная ссылка</a> | <a href="link2" target="_blank">Ссылка в новом окне</a></p> </body> </html> 


The result of the example is shown below (fig. 13.2).

  CSS attribute selectors

Fig. 13.2. Change the style of the element depending on the target value

In this example, the image is added to the link using the background property. Its function is to create a repeating background image, but repeating the background can be canceled through the no-repeat value, which ultimately results in a single image.

Attribute value starts with specific text.

Sets the style for an element if the tag attribute value starts with the specified text. The syntax is as follows.

[attribute ^ = "value"] {Description of style rules}
Selector [attribute ^ = "value"] {Description of style rules}

In the first case, the style is applied to all elements whose attribute values ​​begin with the specified text. And in the second - only to certain selectors. The use of quotes is not necessary, but only if the value contains Latin letters and no spaces.

Suppose that the site is required to separate the style of normal and external links - links that lead to other sites. In order not to introduce a new class in the <a> tag, let's use attribute selectors. External links are characterized by adding to the protocol address, for example, HTTP is used to access hypertext documents. Therefore, external links begin with the keyword http: //, and add it to the selector A, as shown in Example 13.3.

Example 13.3. Changing the style of an external link

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Селекторы атрибутов</title> <style> A[href^="http://"] { font-weight: bold /* Жирное начертание */ } </style> </head> <body> <p><a href="1.html">Обычная ссылка</a> | <a href="http://htmlbook.ru" target="_blank">Внешняя ссылка на сайт htmlbook.ru</a></p> </body> </html> 


The result of the example is shown below (fig. 13.3).

  CSS attribute selectors

Fig. 13.3. Style change for external links

In this example, external links are highlighted in bold. You can also use the technique shown in Example 13.2 and add a small image to the link that will inform you that the link leads to another site.

Attribute value ends with specific text.

Sets the style for an element if the attribute value ends with the specified text. The syntax is as follows.

[attribute $ = "value"] {Description of style rules}
Selector [attribute $ = "value"] {Description of style rules}

In the first case, the style is applied to all elements whose attribute value is completed with the specified text. And in the second - only to certain selectors.

In this way, you can automatically divide the style for links to sites of the domain ru and for links to sites of other domains like com, as shown in Example 13.4.

Example 13.4. Style for different domains

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Селекторы атрибутов</title> <style> A[href$=".ru"] { /* Если ссылка заканчивается на .ru */ background: url(images/ru.png) no-repeat 0 6px; /* Добавляем фоновый рисунок */ padding-left: 12px; /* Смещаем текст вправо */ } A[href$=".com"] { /* Если ссылка заканчивается на .com */ background: url(images/com.png) no-repeat 0 6px; padding-left: 12px; } </style> </head> <body> <p><a href="http://www.yandex.com">Yandex.Com</a> | <a href="http://www.yandex.ru">Yandex.Ru</a></p> </body> </html> 


This example contains two links leading to different domains - com and ru. Moreover, each such link with the help of styles is added its own background image (Fig. 13.4). Style properties will be applied only for those links, the href attribute of which ends in “.ru” or “.com”. Note that by adding a slash to the domain name (http://www.yandex.ru/) or the address of the page (http://www.yandex.ru/fun.html), we will change the ending and the style will not be applied anymore . In this case, it is better to use the selector, in which the specified text occurs anywhere in the attribute value.

  CSS attribute selectors

Fig. 13.4. Adding pictures to links

The attribute value contains the specified text.

There are options when the style should be applied to a tag with a specific attribute, while some text is part of its value. In this case, it is not known exactly where the text is included in the text - at the beginning, middle or end. In this case, use the following syntax.

[attribute * = "value"] {Description of style rules}
Selector [attribute * = "value"] {Description of style rules}

Example 13.5 shows a change in the style of links in the href attribute of which the word “htmlbook” is found.

Example 13.5. Style for different sites

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Селекторы атрибутов</title> <style> [href*="htmlbook"] { background: yellow; /* Желтый цвет фона */ } </style> </head> <body> <p><a href="http://www.htmlbook.ru/html/">Теги HTML</a> | <a href="http://stepbystep.htmlbook.ru">Шаг за шагом</a> | <a href="http://webimg.ru">Графика для Веб</a></p> </body> </html> 


The result of this example is shown in Fig. 13.5.

  CSS attribute selectors

Fig. 13.5. Changing the style for links whose address contains the “htmlbook”

One of several attribute values

Some attribute values ​​can be listed separated by spaces, for example class names. The following syntax is used to set the style if the list contains the required value.

[attribute ~ = "value"] {Description of style rules}
Selector [attribute ~ = "value"] {Description of style rules}

The style is applied if the attribute has the specified value or it is included in the list of values ​​separated by a space (Example 13.6).

Example 13.6. Style depending on class name

HTML5CSS 2.1IECrOpSa 5Fx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Блок</title> <style> [class~="block"] h3 { color: green; } </style> </head> <body> <div class="block tag"> <h3>Заголовок</h3> </div> </body> </html> 


In this example, the green text color is applied to the H3 selector if the class name of the layer is specified as block. Note that a similar result can be obtained by using the construct * = instead of ~ =.

Hyphen attribute value

In identifier and class names, it is allowed to use the hyphen character (-), which allows you to create meaningful values ​​for the id and class attributes. To change the style of elements in the value of which a hyphen is used, you should use the following syntax.

[attribute | = "value"] {Description of style rules}
Selector [attribute | = "value"] {Description of style rules}

The style is applied to elements whose attribute begins with the specified value or with a fragment of a value, after which there is a hyphen (Example 13.7).

Example 13.7. Hyphens in values

HTML5CSS 2.1IECrOpSaFx

 <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Блок</title> <style> DIV[class|="block"] { background: #306589; /* Цвет фона */ color: #acdb4c; /* Цвет текста */ padding: 5px; /* Поля */ } DIV[class|="block"] A { color: #fff; /* Цвет ссылок */ } </style> </head> <body> <div class="block-menu-therm"> <h2>Термины</h2> <div class="content"> <ul class="menu"> <li><a href="t1.html">Буквица</a></li> <li><a href="t2.html">Выворотка</a></li> <li><a href="t3.html">Выключка</a></li> <li><a href="t4.html">Интерлиньяж</a></li> <li><a href="t5.html">Капитель</a></li> <li><a href="t6.html">Начертание</a></li> <li><a href="t7.html">Отбивка</a></li> </ul> </div> </div> </body> </html> 


In this example, the class name is set as block-menu-therm, so the styles use the | = "block" construction, since the meaning begins with this word and there are hyphens in the meaning.

All of these methods can be combined with each other, defining a style for elements that contain two or more attributes. In such cases, square brackets are consecutive.

[attribute1 = "value1"] [attribute2 = "value2"] {Description of style rules}
Selector [attribute1 = "value1"] [attribute2 = "value2"] {Description of style rules}

Questions to check

1. You need to set the background color of the text field. What style is suitable for this purpose?

  1. INPUT [type = "text"] {background: #acdacc; }
  2. INPUT [type = "textinput"] {background: #acdacc; }
  3. INPUT [type = "textfield"] {background: #acdacc; }
  4. INPUT [type = "textarea"] {background: #acdacc; }
  5. INPUT [type = "texts"] {background: #acdacc; }

2. What style should I use to change the text color only in the second paragraph?

<p class = "text text1-count1-text"> First paragraph </ p>
<p class = "text text2-count2-text"> Second paragraph </ p>
<p class = "text text3-count3-text"> Third paragraph </ p>

  1. P [class | = "text2"] {color: red; }
  2. P [class ^ = "text2"] {color: red; }
  3. P [class ~ = "text2"] {color: red; }
  4. P [class * = "text2"] {color: red; }
  5. P [class $ = "text2"] {color: red; }

3. To which element will the following style be applied?

[class ~ = "lorem"] {background: # 666; }

  1. <p class = "lorem-ipsum"> Lorem ipsum dolor sit amet </ p>
  2. <div class = "lorem-ipsum dolor"> Lorem ipsum dolor sit amet </ div>
  3. <p class = "ipsum-lorem"> Lorem ipsum dolor sit amet </ p>
  4. <div class = "lorem ipsum"> Lorem ipsum dolor sit amet </ div>
  5. <p> <span class = "1orem ipsum"> Lorem ipsum dolor sit amet </ span> </ p>

Answers

1. INPUT [type = "text"] {background: #acdacc; }

2. P [class * = "text2"] {color: red; }

3. <div class = "lorem ipsum"> Lorem ipsum dolor sit amet </ div>

created: 2014-10-19
updated: 2021-03-13
132665



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Cascading CSS / CSS3 Style Sheets

Terms: Cascading CSS / CSS3 Style Sheets