- Тонкости использования селекторов аттрибутов в CSS
- [rel = external] — Точное совпадение значения атрибута
- [rel *= external] — Атрибут содержит некоторое значение в любом месте
- [rel ^= external] — Атрибут начинается с определенного значения
- [rel $= external] — Атрибут оканчивается определенным значением
- [rel ~= external] — Атрибут содержит значение в списке разделенном пробелами
- [rel |= external] — Атрибут содержит значение в списке разделенном тире
- [title = one][rel ^= external] — Совпадение нескольких атрибутов
- Поддержка браузерами
- Attribute selectors
- Syntax
- Examples
- Links
- CSS
- HTML
- Result
- Languages
- CSS
- HTML
- Result
- HTML ordered lists
- CSS
- HTML
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- CSS Attribute Selectors
- CSS [attribute] Selector
- Example
- CSS [attribute=»value»] Selector
- Example
- CSS [attribute~=»value»] Selector
- Example
- CSS [attribute|=»value»] Selector
- Example
- CSS [attribute^=»value»] Selector
- Example
- CSS [attribute$=»value»] Selector
- Example
- CSS [attribute*=»value»] Selector
- Example
- Styling Forms
- Example
- All CSS Attribute Selectors
Тонкости использования селекторов аттрибутов в CSS
Этот один элемент имеет три аттрибута: ID, class и rel. Для выбора элемента в CSS вы можете использовать селектор ID (#first-title) и селектор class (.magical). Но знаете ли вы, что можно использовать для выбора атрибут rel? Это так называемый селектор атрибута:
Существует множество селекторов атрибутов, мы не будем рассматривать все возможные варианты, рассмотрим наиболее полезные сценарии, встречающиеся в реальном мире.
[rel = external] — Точное совпадение значения атрибута
В примере выше, мы использовали атрибут со значением «friend» у элемента h2. CSS селектор, который мы написали, нацелен на элемент h2, потому что его атрибут rel имеет значение «friend». Другими словами, знак равенства означает точное соответствие. Рассмотрим другие примеры.
Более реальный пример из жизни — это стилизация списка блогов. Например у вас есть список ссылок на сайты друзей:
Вы хотите сделать различные стили для каждой из ссылок. Традиционный способ — задать каждой ссылке имя класса, но это требует дополнительной разметки, что не всегда хорошо (для семантики и прочего). Другой способ — это использование :nth-child, но для этого потребуется неизменный порядок списка. В данном случае идеальным решением будет использование селекторов атрибутов… Ссылки уже имеют уникальные атрибуты.
Я думаю, что чаще всего селекторы атрибутов используют для элементов input. Это text, button, checkbox, file, hidden, image, password, radio, reset и submit. Все они являются элементом и все они очень разные. Так что делать, что то вроди input , почти всегда плохая идея. Поэтому очень часто можно увидеть, нечто похожее на это:
Это единственный способ получить различные типы инпутов без добавления дополнительной разметки.
[rel *= external] — Атрибут содержит некоторое значение в любом месте
Именно здесь становится более интересно. Знаку равенства в селекторе атрибута могут предшествовать другие символы изменяющие значение. Например, «* black»> < h1 rel ="xxxexternalxxx" >Attribute Contains
Помните, что классы и ID тоже являются атрибутами, и могут быть использованы селектором атрибута. Допустим вы пишете CSS для сайта в котором вы не можете контролировать разметку и разработчики сделали три дива:
[rel ^= external] — Атрибут начинается с определенного значения
Реальным примером использования может быть случай, когда вам нужно, что бы любая ссылка на сайт друга отличалась от других ссылок. Не важно это ссылка на главную страницу или внутреннюю, стиль должен быть одним.
Это будет соответствовать ссылке на главную и второстепенные страницы.
[rel $= external] — Атрибут оканчивается определенным значением
Честно говоря, я изо всех сил пытаюсь найти реальный пример использования этого. К примеру вы можете найти ссылки имеющие в конце определенные символы.
[rel ~= external] — Атрибут содержит значение в списке разделенном пробелами
Вы наверняка знаете, что к элементу можно применять несколько классов. Если вы это сделаете, вы можете использовать .class-name в CSS для связи. В селекторе атрибута не все так просто. Если ваш атрибут имеет несколько значений (например список разделенный пробелами) вам прийдется использовать «~ black»> < h1 rel ="friend external sandwich" >Attribute Space Separated
Вы можете подумать, зачем это использовать, когда «* home friend-link» , другой rel=»home friend link» . Вам понадобится селектор разделенный пробелами для связи с вторым элементом.
[rel |= external] — Атрибут содержит значение в списке разделенном тире
Список разделенный тире очень похож на список разделенный пробелами, и его так же используют для более строгого соблюдения правил, чем при использовании *=.
[title = one][rel ^= external] — Совпадение нескольких атрибутов
Вы можете использовать несколько селекторов атрибутов в одном селекторе, который требуют совпадения от всех условий.
Поддержка браузерами
Каждый приведенный выше пример работает во всех современных браузерах: Safari, Chrome, Firefox, Opera и IE. Internet Explorer обладает превосходной поддержкой всего этого в 7 версии и нулевой поддержкой в 6 версии. Что бы протестировать в браузере — откройте тестовую страницу. Если строка/селектор красная — значит селектор работает.
Attribute selectors
The CSS attribute selector matches elements based on the element having a given attribute explicitly set, with options for defining an attribute value or substring value match.
The case sensitivity of attribute names and values depends on the document language. In HTML, attribute names are case insensitive, as are spec-defined enumerated values. The case-insensitive HTML attribute values are listed in the HTML spec. For these attributes, the attribute value in the selector is case-insensitive, regardless of whether the value is invalid or the attribute for the element on which it is set is invalid.
If the attribute value is case sensitive, like class , id , and data-* attributes, the attribute selector value match is case-sensitive. Attributes defined outside of the HTML specification, like role and aria-* attributes, are also case-sensitive. Normally case-sensitive attribute selectors can be made case-insensitive with the inclusion of the case-insensitive modifier ( i ).
Syntax
Represents elements with an attribute name of attr.
Represents elements with an attribute name of attr whose value is exactly value.
Represents elements with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly value.
Represents elements with an attribute name of attr whose value can be exactly value or can begin with value immediately followed by a hyphen, — (U+002D). It is often used for language subcode matches.
Represents elements with an attribute name of attr whose value is prefixed (preceded) by value.
Represents elements with an attribute name of attr whose value is suffixed (followed) by value.
Represents elements with an attribute name of attr whose value contains at least one occurrence of value within the string.
Adding an i (or I ) before the closing bracket causes the value to be compared case-insensitively (for characters within the ASCII range).
[attr operator value s] ExperimentalAdding an s (or S ) before the closing bracket causes the value to be compared case-sensitively (for characters within the ASCII range).
Examples
Links
CSS
a color: blue; > /* Internal links, beginning with "#" */ a[href^="#"] background-color: gold; > /* Links with "example" anywhere in the URL */ a[href*="example"] background-color: silver; > /* Links with "insensitive" anywhere in the URL, regardless of capitalization */ a[href*="insensitive" i] color: cyan; > /* Links with "cAsE" anywhere in the URL, with matching capitalization */ a[href*="cAsE" s] color: pink; > /* Links that end in ".org" */ a[href$=".org"] color: red; > /* Links that start with "https://" and end in ".org" */ a[href^="https://"][href$=".org"] color: green; >
HTML
ul> li>a href="#internal">Internal linka>li> li>a href="http://example.com">Example linka>li> li>a href="#InSensitive">Insensitive internal linka>li> li>a href="http://example.org">Example org linka>li> li>a href="https://example.org">Example https org linka>li> ul>
Result
Languages
CSS
/* All divs with a `lang` attribute are bold. */ div[lang] font-weight: bold; > /* All divs without a `lang` attribute are italicized. */ div:not([lang]) font-style: italic; > /* All divs in US English are blue. */ div[lang~="en-us"] color: blue; > /* All divs in Portuguese are green. */ div[lang="pt"] color: green; > /* All divs in Chinese are red, whether simplified (zh-Hans-CN) or traditional (zh-Hant-TW). */ div[lang|="zh"] color: red; > /* All divs with a Traditional Chinese `data-lang` are purple. */ /* Note: You could also use hyphenated attributes without double quotes */ div[data-lang="zh-Hant-TW"] color: purple; >
HTML
div lang="en-us en-gb en-au en-nz">Hello World!div> div lang="pt">Olá Mundo!div> div lang="zh-Hans-CN">世界您好!div> div lang="zh-Hant-TW">世界您好!div> div data-lang="zh-Hant-TW">世界您好!div>
Result
HTML ordered lists
The HTML specification requires the type attribute to be matched case-insensitively because it is primarily used in the element. Note that if a modifier is not supported by the user agent, then the selector will not match.
CSS
/* Case-sensitivity depends on document language */ ol[type="a"] list-style-type: lower-alpha; background: red; > ol[type="b" s] list-style-type: lower-alpha; background: lime; > ol[type="B" s] list-style-type: upper-alpha; background: grey; > ol[type="c" i] list-style-type: upper-alpha; background: green; >
HTML
ol type="A"> li> Red background for case-insensitive matching (default for the type selector) li> ol> ol type="b"> li>Lime background if `s` modifier is supported (case-sensitive match)li> ol> ol type="B"> li>Grey background if `s` modifier is supported (case-sensitive match)li> ol> ol type="C"> li> Green background if `i` modifier is supported (case-insensitive match) li> ol>
Result
Specifications
Browser compatibility
BCD tables only load in the browser
See also
- attr()
- Selecting a single element: Document.querySelector() , DocumentFragment.querySelector() , or Element.querySelector()
- Selecting all matching elements: Document.querySelectorAll() , DocumentFragment.querySelectorAll() , or Element.querySelectorAll()
- Case-insensitive attribute selector values on WHATWG
Found a content problem with this page?
This page was last modified on Jun 29, 2023 by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
CSS Attribute Selectors
It is possible to style HTML elements that have specific attributes or attribute values.
CSS [attribute] Selector
The [attribute] selector is used to select elements with a specified attribute.
The following example selects all elements with a target attribute:
Example
CSS [attribute=»value»] Selector
The [attribute=»value»] selector is used to select elements with a specified attribute and value.
Example
CSS [attribute~=»value»] Selector
The [attribute~=»value»] selector is used to select elements with an attribute value containing a specified word.
The following example selects all elements with a title attribute that contains a space-separated list of words, one of which is «flower»:
Example
The example above will match elements with title=»flower», title=»summer flower», and title=»flower new», but not title=»my-flower» or title=»flowers».
CSS [attribute|=»value»] Selector
The [attribute|=»value»] selector is used to select elements with the specified attribute, whose value can be exactly the specified value, or the specified value followed by a hyphen (-).
Note: The value has to be a whole word, either alone, like class=»top», or followed by a hyphen( — ), like >
Example
CSS [attribute^=»value»] Selector
The [attribute^=»value»] selector is used to select elements with the specified attribute, whose value starts with the specified value.
The following example selects all elements with a class attribute value that starts with «top»:
Note: The value does not have to be a whole word!
Example
CSS [attribute$=»value»] Selector
The [attribute$=»value»] selector is used to select elements whose attribute value ends with a specified value.
The following example selects all elements with a class attribute value that ends with «test»:
Note: The value does not have to be a whole word!
Example
CSS [attribute*=»value»] Selector
The [attribute*=»value»] selector is used to select elements whose attribute value contains a specified value.
The following example selects all elements with a class attribute value that contains «te»:
Note: The value does not have to be a whole word!
Example
Styling Forms
The attribute selectors can be useful for styling forms without class or ID:
Example
input[type=»text»] <
width: 150px;
display: block;
margin-bottom: 10px;
background-color: yellow;
>
input[type=»button»] width: 120px;
margin-left: 35px;
display: block;
>
Tip: Visit our CSS Forms Tutorial for more examples on how to style forms with CSS.
All CSS Attribute Selectors
Selector | Example | Example description |
---|---|---|
[attribute] | [target] | Selects all elements with a target attribute |
[attribute=value] | [target=»_blank»] | Selects all elements with target=»_blank» |
[attribute~=value] | [title~=»flower»] | Selects all elements with a title attribute containing the word «flower» |
[attribute|=value] | [lang|=»en»] | Selects all elements with a lang attribute value starting with «en» |
[attribute^=value] | a[href^=»https»] | Selects every element whose href attribute value begins with «https» |
[attribute$=value] | a[href$=».pdf»] | Selects every element whose href attribute value ends with «.pdf» |
[attribute*=value] | a[href*=»w3schools»] | Selects every element whose href attribute value contains the substring «w3schools» |