Css attribute selectors not

CSS-селектор :not. Полезные примеры

В спецификации и блогах про селектор :not обычно приводят какие-то искусственные примеры, которые хоть и объясняют синтаксис и принцип действия, но не несут никакой идеи о том, как получить пользу от нового селектора.

Ну окей, думаю я, в моей практике не встречались такие ситуации. Обходились мы ведь как-то раньше без :not . Приходилось немного переписать структуру селекторов или обнулить пару значений.

Пример 1. Элемент без класса

Селектор :not может быть крайне полезен, когда нам нужно застилить контент сгенерированный пользователем (нет возможности расставить в нем классы), или когда у нас контента очень много и расставлять в нем классы слишком трудоёмко.

Например, мы хотим на сайте сделать красивые буллиты для ненумерованных списков ul li . Мы пишем код:

ul li < /* наши красивые стили */ > 

В результате, наши красивые буллиты появляются не только в контенте, но и, например, в навигации, где тоже используются ul li .

Мы ограничиваем область действия селектора:

Навигацию мы спасли, но ненужные буллиты всё еще вылазят на слайдерах, списках новостей и других конструкциях внутри .content , где тоже используются ul li .

1) обнулить мешающие стили в слайдерах и других местах. Но это противоречит « DRY » и является одним из признаков «вонючего» кода. К тому же не решает проблему раз и навсегда: добавите, например, аккордеон и списки в нем снова придется обнулять.

2) пойти от обратного и ставить класс всем спискам, которые нужно стилизовать:

Это добавляет лишней работы по расстановке классов в контенте. Иногда имеет смысл, но лишнюю работу никто не любит.

3) стилизовать только те ul li , у которых нет никаких классов вообще:

Победа! Нам не нужно делать дополнительную работу по расстановке классов в контенте. А на слайдерах, аккордеонах и прочих конструкциях, которые не должны выглядеть как списки, но используют их в своей разметке, в 99% случаев уже будут свои классы, и наши стили их не затронут.

Этот прием — «выбирать только элементы без класса» — очень полезен для оформления пользовательского контента и его можно применять не только к спискам, но и для других случаев.

Пример 2. Изменение внешнего вида всех элементов, кроме наведенного

Такой эффект можно реализовать без :not путем перезаписи значений. И это будет работать в бо́льшем количестве браузеров.

/* с перезаписью свойств */ ul:hover li < opacity:0.5; > ul:hover li:hover < opacity:1; > 

Но если придется обнулять слишком много свойств, то есть смысл использовать :not .

/* используя :not() */ ul:hover li:not(:hover) < opacity:0.5; > 

Пример 3. Меню с разделителями между элементами

Меню с разделителями между элементами

Как и в предыдущем примере, желаемого можно добиться несколькими способами.

Читайте также:  Javascript css font size

Через перезапись свойств. Но тут два правила вместо одного, что не есть « DRY ».

.menu-item:after < content: ' | '; > .menu-item:last-child:after < content: none; > 

Через :nth-last-child() . Одно правило, но тяжело читается.

.menu-item:nth-last-child(n+2):after < content: ' | '; > 

Через :not() — самая короткая и понятная запись.

.menu-item:not(:last-child):after < content: ' | '; > 

Пример 4. Debug css

Удобно для отладки и самоконтроля искать/подсвечивать картинки без alt, label без for и другие ошибки.

/* подсвечиваем теги без необходимых атрибутов */ img:not([alt]), label:not([for]), input[type=submit]:not([value]) < outline:2px solid red; > /* тревога, если первый child внутри списка не li и прочие похожие примеры */ ul > *:not(li), ol > *:not(li), dl > *:not(dt):not(dd) < outline:2px solid red; > 

Пример 5. Поля форм

Раньше текстовых полей форм было не много. Достаточно было написать:

select, textarea, [type="text"], [type="password"] < /* стили для текстовых полей ввода */ > 

С появлением новых типов полей в HTML5 этот список увеличился:

select, textarea, [type="text"], [type="password"], [type="color"], [type="date"], [type="datetime"], [type="datetime-local"], [type="email"], [type="number"], [type="search"], [type="tel"], [type="time"], [type="url"], [type="month"], [type="week"] < /* стили для текстовых полей ввода */ > 

Вместо перечисления 14 типов инпутов можно исключить 8 из них:

select, textarea, [type]:not([type="checkbox"]):not([type="radio"]):not([type="button"]):not([type="submit"]):not([type="reset"]):not([type="range"]):not([type="file"]):not([type="image"]) < /* стили для текстовых полей ввода */ > 

Ладно, этот пример не очень красив, и я рекомендую всё же первый вариант с перечислением, он работает с IE8+, а второй вариант с IE9+.

Поддержка

Следует заметить, что согласно спецификации в скобках селектора :not() может стоять только простой селектор и в скобках нельзя использовать сам селектор :not() . Если нужно исключить несколько элементов, :not() можно повторить несолько раз, как в примере 5.

Если очень нужны CSS3-селекторы в браузерах, которые их не поддерживают, можно использовать полифил selectivizr.

Источник

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] Experimental

Adding an s (or S ) before the closing bracket causes the value to be compared case-sensitively (for characters within the ASCII range).

Examples

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.

Источник

How to select HTML element without attribute with CSS?

There might be cases, where You want to select element that does not have particular attribute. Not have attribute might actually mean two different aspects. One could consider empty attribute like if it not exists, while other would said that the element have attribute but empty. We will focus here on case where we treat both empty or non existent attribute as non existent.

The use case here is to select all bare links, in other words those links that do not have any CSS class applied. To select those elements, we need to use attribute selector twice, once assuming empty content and the other one assuming no attribute at all. To select elements without attribute we can use not selector extension while for empty attribute attribute just CSS attribute selector with empty value.

Example

Selecting all a elements that do not have CSS class applied:

The first selector selects all a elements that do not have class attribute, the latter one selects all with empty class attribute. The same technique can be used to select any other elements with empty attribute.

The selector will match for example:

Selecting Elements That Don’t Have Particular Attribute or Have It Empty

As in class example we need to combine not attribute selector with empty attribute selector:

This will match any div element without (or empty) id attribute:

But will not match if element have any value on id attribute:

Selecting Elements That Don’t Have Particular Attribute

The slightly different case is when selecting element that do not have attribute. The empty value means that attribute is empty but it still exists. To select such elements we will use only not operator.

For example let’s use data-name custom attribute selector:

This will match elements that do not have data-name attribute:

But it will not match those which have empty data-name attribute:

Источник

Оцените статью