JavaRush /Java Blog /Random EN /Attribute selectors
articles
Level 15

Attribute selectors

Published in the Random EN group
To change the style of elements containing various parameters, attribute selectors have been introduced into CSS. They allow you to set the style of a tag based on the presence of a certain parameter or its value. Attribute selectors - 1Note: Attribute selectors are supported by Internet Explorer version 7.0 and later, and the correct <!DOCTYPE> must be added for the examples to work correctly. Let's look at several typical uses of such selectors.

Simple attribute selector

Sets the style for an element if a specific attribute is specified. Its meaning is not important in this case. The syntax for using such a selector is as follows.
[атрибут] { Описание правил стиля } Селектор[атрибут] { Описание правил стиля }
Space between the selector name and square brackets is not allowed. Example 12.1 shows how the <Q> tag is styled when a title parameter is added to it. Example 12.1. Type of element depending on its parameter
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
  <title>Селекторы атрибутов</title>
  <style type="text/css">
   Q {
    font-style: italic; /* Курсивное начертание */
    quotes: "\00AB" "\00BB"; /* Меняем вид кавычек в цитате */
   }
   Q[title] {
    color: maroon; /* Цвет текста */
   }
  </style>
 </head>
 <body>
  <p>Продолжая известный закон Мерфи, который гласит: <q>Если неприятность
  может случиться, то она обязательно случится</q>, можем ввести свое наблюдение:
  <q title="Из законов Фергюсона-Мержевича">После
  того, How веб-page будет корректно отображаться в одном браузере, выяснится,
  что она неправильно показывается в другом</q>.</p>
 </body>
</html>
The result of the example is shown in Fig. 12.1 Attribute selectors - 2 In this example, the color of the text inside the 7lt;Q> container changes when the title parameter is added to it. Note that for the Q[title] selector there is no need to repeat the attributes since they are inherited from the Q selector.

Attribute selector with value

Sets the style for an element if a specific value is specified for a specific parameter. The application syntax is as follows.
[атрибут="meaning"] { Описание правил стиля } Селектор[атрибут="meaning"] { Описание правил стиля }
In the first case, the style is applied to all elements that contain the specified attribute value. And in the second - only to certain selectors. Example 12.2 shows how to change the link style if the A tag contains a parameter target="_blank". In this case, the link will open in a new window and to show this, using styles we add a small picture in front of the link text. Example 12.2. Style for opening links in a new window
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
  <title>Селекторы атрибутов</title>
  <style type="text/css">
   A[target="_blank"] {
    background: url(blank.gif) no-repeat 0 2px; /* Параметры фонового рисунка */
    padding-left: 15px; /* Смещаем текст вправо */
   }
  </style>
 </head>
 <body>
  <p><a href="link1.html">Обычная link</a> |
     <a href="link2" target="_blank">Ссылка в новом окне</a></p>
 </body>
</html>
The result of the example is shown below (Figure 12.2). Attribute selectors - 3In this example, a picture is added to the link using the attribute background. Its function is to create a repeating background image, but the background repetition can be canceled via the argument no-repeat, resulting in a single image.

Attribute starts with a specific value

Sets the style for an element if the attribute begins with the specified value. The application syntax is as follows.
[атрибут^="meaning"] { Описание правил стиля } Селектор[атрибут^="meaning"] { Описание правил стиля }
In the first case, the style is applied to all elements that begin with the specified attribute value. And in the second - only to certain selectors. Let's assume that your site needs to separate the style of regular and external links—links that lead to other sites. To avoid adding Aa new class to the tag, we will use attribute selectors. External links are characterized by adding a protocol to the address, for example, the HTTP protocol is used to access hypertext documents. Therefore, external links begin with the keyword http://, and we add it to the selector A, as shown in example 12.3. Example 12.3. Changing the xref style
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
  <title>Селекторы атрибутов</title>
  <style type="text/css">
   A[href^="http://"] {
    font-weight: bold; /* Жирное начертание */
   }
  </style>
 </head>
 <body>
  <p><a href="link1.html">Обычная link</a> |
  <a href="http://htmlbook.ru" target="_blank" rel="nofollow" >Внешняя link на сайт htmlbook.ru</a></p>
 </body>
</html>
The result of the example is shown below (Fig. 12.3) Attribute selectors - 4 In this example, external links are highlighted in bold. You can also use the technique shown in Example 12.2 and add a small image to the link, which will indicate that the link leads to another site.

The attribute ends with a specific value

Sets the style for an element if the attribute ends with the specified value. The application syntax is as follows.
[атрибут$="meaning"] { Описание правил стиля } Селектор[атрибут$="meaning"] { Описание правил стиля }
In the first case, the style is applied to all elements that end with the specified attribute value. And in the second - only to certain selectors. In this way, you can automatically separate the style for sites of the ru domain and for sites of other domains like com, as shown in example 12.4. Example 12.4. Style for different domains
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
  <title>Селекторы атрибутов</title>
  <style type="text/css">
   A[href$=".ru"] { /* Если link заканчивается на .ru */
    background: url(ru.gif) no-repeat; /* Параметры фонового рисунка */
    padding-left: 10px; /* Смещаем текст вправо */
   }
   A[href$=".com"] { /* Если link заканчивается на .com */
    background: url(com.gif) no-repeat;
    padding-left: 10px;
   }
  </style>
 </head>
 <body>
  <p><a href="http://www.yandex.com" rel="nofollow" >Yandex.Com</a> |
  <a href="http://www.yandex.ru" rel="nofollow" >Yandex.Ru</a></p>
 </body>
</html>
This example contains two links leading to different domains - comand ru. At the same time, each such link has its own background image added using styles. Style attributes will be added only for those links hrefwhose parameter ends in “.ru” or “.com”. Please note that by adding a slash ( http://www.yandex.ru/ ) or the page address ( http://www.yandex.ru/fun.html ) to the domain name, we will thereby change the ending and the style will not be applied. In this case, it is better to use a selector in which a specific value can be located anywhere in the attribute.

The value occurs anywhere in the attribute

There are options when the style should be applied to a selector with a specific attribute, of which a value is part. However, it is not known exactly whether the argument begins or ends with this value. Then the following syntax should be used.
[атрибут*="meaning"] { Описание правил стиля } Селектор[атрибут*="meaning"] { Описание правил стиля }
The value can appear anywhere in the argument, such as at the beginning, end, or somewhere in between. The main thing is that it is part of it. Thus, Example 12.5 shows a change in the style of links in which the word “htmlbook” appears. Example 12.5. Style for different sites
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
  <title>Селекторы атрибутов</title>
  <style type="text/css">
   [href*="htmlbook"] {
    background: yellow; /* Желтый цвет фона */
   }
  </style>
 </head>
 <body>
  <p><a href="http://www.htmlbook.ru/html/" rel="nofollow" >Tagи HTML</a> |
  <a href="http://stepbystep.htmlbook.ru" rel="nofollow" >Шаг за шагом</a> |
  <a href="http://webimg.ru" rel="nofollow" >Графика для Веб</a></p>
 </body>
</html>
The result of this example is shown in Fig. 12.4 Attribute selectors - 5 There are some other types of argument selectors, but they are used quite rarely, so we will omit their description. Link to the original source: http://stepbystep.htmlbook.ru/?id=54
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION