- CSS-селекторы
- Базовые селекторы
- Комбинаторы
- Псевдо
- Версии CSS
- Смотрите также
- Found a content problem with this page?
- Css selector not tag
- Try it
- Syntax
- Description
- Examples
- Using :not() with valid selectors
- HTML
- CSS
- Result
- Using :not() with invalid selectors
- HTML
- CSS
- Result
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- A Complete Guide to How the CSS not Selector Works
- CSS not Selector
- CSS not Selectors Increase Specificity
- CSS not Selectors and the DOM structure
- CSS not Selector Support
CSS-селекторы
Селектор определяет, к какому элементу применять то или иное CSS-правило.
Обратите внимание — не существует селекторов, которые бы позволили выбрать родителя (содержащий контейнер) или соседа родителя или потомков соседа родителя.
Базовые селекторы
Выбирает все элементы. По желанию, он может быть ограничен определённым пространством имён или относиться ко всему пространству имён.
Синтаксис: * ns|* *|*
Пример: * будет соответствовать всем элементам на странице.
Этот базовый селектор выбирает тип элементов, к которым будет применяться правило.
Синтаксис: элемент
Пример: селектор input выберет все элементы .
Этот базовый селектор выбирает элементы, основываясь на значении их атрибута class .
Синтаксис: .имяКласса
Пример: селектор .index выберет все элементы с соответствующим классом (который был определён в атрибуте class=»index» ).
Этот базовый селектор выбирает элементы, основываясь на значении их id атрибута. Не забывайте, что идентификатор должен быть уникальным, т. е. использоваться только для одного элемента в HTML-документе.
Синтаксис: #имяИдентификатора
Пример: селектор #toc выберет элемент с идентификатором toc (который был определён в атрибуте id=»toc» ).
Этот селектор выбирает все элементы, имеющие данный атрибут или атрибут с определённым значением.
Синтаксис: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value] [attr*=value]
Пример: селектор [autoplay] выберет все элементы, у которых есть атрибут autoplay (независимо от его значения).
Ещё пример: a[href$=».jpg»] выберет все ссылки, у которых адрес заканчивается на «.jpg».
Ещё пример: a[href^=»https»] выберет все ссылки, у которых адрес начинается на «https».
Комбинаторы
Комбинатор , это способ группировки, он выбирает все совпадающие узлы.
Синтаксис: A, B
Пример: div, span выберет оба элемента — и и .
Комбинатор ‘ ‘ (пробел) выбирает элементы, которые находятся внутри указанного элемента (вне зависимости от уровня вложенности).
Синтаксис: A B
Пример: селектор div span выберет все элементы , которые находятся внутри элемента .
Комбинатор ‘>’ в отличие от пробела выбирает только те элементы, которые являются дочерними непосредственно по отношению к указанному элементу.
Синтаксис: A > B
Комбинатор ‘~’ выбирает элементы, которые находятся на этом же уровне вложенности, после указанного элемента, с тем же родителем.
Синтаксис: A ~ B
Комбинатор ‘+’ выбирает элемент, который находится непосредственно после указанного элемента, если у них общий родитель.
Синтаксис: A + B
Пример: селектор h2 + p выберет первый элемент , который находится непосредственно после элемента (en-US).
Псевдо
Знак : позволяет выбрать элементы, основываясь на информации, которой нет в дереве элементов.
Пример: a:visited соответствует всем элементам которые имеют статус «посещённые».
Ещё пример: div:hover соответствует элементу, над которым проходит указатель мыши.
Ещё пример: input:focus соответствует полю ввода, которое получило фокус.
Знак :: позволяет выбрать вещи, которых нет в HTML.
Пример: p::first-line соответствует первой линии абзаца .
Версии CSS
Спецификация | Статус | Комментарии |
---|---|---|
Selectors Level 4 | Рабочий черновик | Добавление комбинатора колонок || , селекторов структуры сеточной разметки (CSS grid selector), логических комбинаторов, местоположения, временных, состояния ресурсов, лингвистических и UI псевдоклассов, модификаторов для ASCII регистрозависимых и регистронезависимых атрибутов со значениями и без них. |
Selectors Level 3 | Рекомендация | Добавлен комбинатор ~ и древовидные структурные псевдоклассы. Сделаны псевдоэлементы, использующие префикс :: двойное двоеточие. Селекторы дополнительных атрибутов. |
CSS Level 2 (Revision 1) | Рекомендация | Добавлен комбинатор потомков > и комбинатор следующего соседа + . Добавлен универсальный (*) комбинатор и селектор атрибутов. |
CSS Level 1 | Рекомендация | Первоначальное определение. |
Смотрите также
Found a content problem with this page?
This page was last modified on 22 июл. 2023 г. by MDN contributors.
Your blueprint for a better internet.
Css selector not tag
The :not() CSS pseudo-class represents elements that do not match a list of selectors. Since it prevents specific items from being selected, it is known as the negation pseudo-class.
Try it
The :not() pseudo-class has a number of quirks, tricks, and unexpected results that you should be aware of before using it.
Syntax
The :not() pseudo-class requires a comma-separated list of one or more selectors as its argument. The list must not contain another negation selector or a pseudo-element.
Description
There are several unusual effects and outcomes when using :not() that you should keep in mind when using it:
- Useless selectors can be written using this pseudo-class. For example, :not(*) matches any element which is not an element, which is obviously nonsense, so the accompanying rule will never be applied.
- This pseudo-class can increase the specificity of a rule. For example, #foo:not(#bar) will match the same element as the simpler #foo , but has the higher specificity of two id selectors.
- The specificity of the :not() pseudo-class is replaced by the specificity of the most specific selector in its comma-separated argument of selectors; providing the same specificity as if it had been written :not(:is(argument)) .
- :not(.foo) will match anything that isn’t .foo , including and .
- This selector will match everything that is «not an X». This may be surprising when used with descendant combinators, since there are multiple paths to select a target element. For instance, body :not(table) a will still apply to links inside a , since , , , , , etc. can all match the :not(table) part of the selector.
- You can negate several selectors at the same time. Example: :not(.foo, .bar) is equivalent to :not(.foo):not(.bar) .
- If any selector passed to the :not() pseudo-class is invalid or not supported by the browser, the whole rule will be invalidated. The effective way to overcome this behavior is to use :is() pseudo-class, which accepts a forgiving selector list. For example :not(.foo, :invalid-pseudo-class) will invalidate a whole rule, but :not(:is(.foo, :invalid-pseudo-class)) will match any (including and ) element that isn’t .foo .
Examples
Using :not() with valid selectors
This example shows some simple cases of using :not() .
HTML
p>I am a paragraph.p> p class="fancy">I am so very fancy!p> div>I am NOT a paragraph.div> h2> span class="foo">foo inside h2span> span class="bar">bar inside h2span> h2>
CSS
.fancy text-shadow: 2px 2px 3px gold; > /* elements that don't have a class `.fancy` */
p:not(.fancy) color: green; > /* Elements that are not elements */
body :not(p) text-decoration: underline; > /* Elements that are not s or `.fancy` */ body :not(div):not(.fancy) font-weight: bold; > /* Elements that are not s or `.fancy` */ body :not(div, .fancy) text-decoration: overline underline; > /* Elements inside an that aren't a with a class of `.foo` */ h2 :not(span.foo) color: red; >
Result
Using :not() with invalid selectors
This example shows the use of :not() with invalid selectors and how to prevent invalidation.
HTML
p class="foo">I am a paragraph with .foop> p class="bar">I am a paragraph with .barp> div>I am a div without a classdiv> div class="foo">I am a div with .foodiv> div class="bar">I am a div with .bardiv> div class="foo bar">I am a div with .foo and .bardiv>
CSS
/* Invalid rule, does nothing */ p:not(.foo, :invalid-pseudo-class) color: red; font-style: italic; > /* Select allelements without the `foo` class */
p:not(:is(.foo, :invalid-pseudo-class)) color: green; border-top: dotted thin currentcolor; > /* Select all elements without the `foo` or the `bar` class */ div:not(.foo, .bar) color: red; font-style: italic; > /* Select all elements without the `foo` or the `bar` class */ div:not(:is(.foo, .bar)) border-bottom: dotted thin currentcolor; >
Result
The p:not(.foo, :invalid-pseudo-class) rule is invalid because it contains an invalid selector. The :is() pseudo-class accepts a forgiving selector list, so the :is(.foo, :invalid-pseudo-class) rule is valid and equivalent to :is(.foo) . Thus, the p:not(:is(.foo, :invalid-pseudo-class)) rule is valid and equivalent to p:not(.foo) .
If :invalid-pseudo-class was a valid selector, the first two rules above would still be equivalent (the last two rules showcase that). The use of :is() makes the rule more robust.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 18, 2023 by MDN contributors.
Your blueprint for a better internet.
A Complete Guide to How the CSS not Selector Works
In CSS, it’s often necessary to sign post that we want to select an element, but not in specific circumstances — like if it has a certain class. In these instances, we can use the :not() selector to do that. Let’s look at how it works.
CSS not Selector
The CSS :not() selector is broadly supported by most browsers. The way it works, is that we create a selector, and then specify what it should not be. For example, say you have the following HTML:
class="not-red">Not Red class="not-red">Not Red Red Red
We have a bunch of div s here, and some shouldn’t be red. If we want all div s in general on our page to be red, except for .not-red elements, we can use :not(.not-red) to ensure they remain, well, not red:
Here’s another example. By default, all elements will have the Arial font — except for .old-fashioned elements:
class="old-fashioned">Old Fashioned Text Some Text
div:not(.old-fashioned) font-family: Arial, sans-serif; >
CSS not Selectors Increase Specificity
You might be familiar with the concept of specificity in CSS, where certain selectors «override» others. For example, a class has a lower specificity than an id , so any id CSS properties will override class properties on the same element. The :not selector also affects specificity. For example, if you had div:not(#id) in your code, it still counts as having an id , so the specificity increases as if it has an id . This is useful to remember when using :not()
CSS not Selectors and the DOM structure
One confusing thing about :not() , is when you try to use it to stop styles applying to things within elements. For example, suppose you have the following HTML:
class="container"> class="input-element"> type="text" /> class="input-element"> type="text" />
Let’s say you want to apply a style to only input elements which are not within form elements. Simple, right? You might try something like this:
div :not(form) input border: 2px solid red; >
Only this won’t work, and the reason why is that :not() is applied at every level — and we are wrapping each input in .input-element . That means that :not(form) is applied to .input-element , and it is indeed, not a form. So both input elements will have a red border. To avoid that, you need to remove the wrapper element and have the input be a direct child of the form:
class="container"> type="text" /> type="text" />
CSS not Selector Support
However, things like the following are only available with complex selectors:
Fortunately, support for complex selectors is still quite high. The only browser not supporting complex selectors today, is Internet Explorer and some mobile browsers. You can see the full support for the :not selector here.