- CSS-селекторы
- Базовые селекторы
- Комбинаторы
- Псевдо
- Версии CSS
- Смотрите также
- Found a content problem with this page?
- CSS selectors
- What is a selector?
- Selector lists
- Types of selectors
- Type, class, and ID selectors
- CSS Selectors
- CSS Selectors
- The CSS element Selector
- Example
- The CSS id Selector
- Example
- The CSS class Selector
- Example
- Example
- Example
- The CSS Universal Selector
- Example
- The CSS Grouping Selector
- Example
- All CSS Simple Selectors
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 selectors
In CSS, selectors are used to target the HTML elements on our web pages that we want to style. There are a wide variety of CSS selectors available, allowing for fine-grained precision when selecting elements to style. In this article and its sub-articles we’ll run through the different types in great detail, seeing how they work.
Prerequisites: | Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) |
---|---|
Objective: | To learn how CSS selectors work in detail. |
What is a selector?
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector.
In other articles you may have met some different selectors, and learned that there are selectors that target the document in different ways — for example by selecting an element such as h1 , or a class such as .special .
In CSS, selectors are defined in the CSS Selectors specification; like any other part of CSS they need to have support in browsers for them to work. The majority of selectors that you will come across are defined in the Level 3 Selectors specification and Level 4 Selectors specification, which are both mature specifications, therefore you will find excellent browser support for these selectors.
Selector lists
If you have more than one thing which uses the same CSS then the individual selectors can be combined into a selector list so that the rule is applied to all of the individual selectors. For example, if I have the same CSS for an h1 and also a class of .special , I could write this as two separate rules.
h1 color: blue; > .special color: blue; >
I could also combine these into a selector list, by adding a comma between them.
White space is valid before or after the comma. You may also find the selectors more readable if each is on a new line.
In the live example below try combining the two selectors which have identical declarations. The visual display should be the same after combining them.
When you group selectors in this way, if any selector is syntactically invalid, the whole rule will be ignored.
In the following example, the invalid class selector rule will be ignored, whereas the h1 would still be styled.
h1 color: blue; > ..special color: blue; >
When combined however, neither the h1 nor the class will be styled as the entire rule is deemed invalid.
Types of selectors
There are a few different groupings of selectors, and knowing which type of selector you might need will help you to find the right tool for the job. In this article’s subarticles we will look at the different groups of selectors in more detail.
Type, class, and ID selectors
This group includes selectors that target an HTML element such as an .
It also includes selectors which target a class:
CSS Selectors
A CSS selector selects the HTML element(s) you want to style.
CSS Selectors
CSS selectors are used to «find» (or select) the HTML elements you want to style.
We can divide CSS selectors into five categories:
- Simple selectors (select elements based on name, id, class)
- Combinator selectors (select elements based on a specific relationship between them)
- Pseudo-class selectors (select elements based on a certain state)
- Pseudo-elements selectors (select and style a part of an element)
- Attribute selectors (select elements based on an attribute or attribute value)
This page will explain the most basic CSS selectors.
The CSS element Selector
The element selector selects HTML elements based on the element name.
Example
Here, all
elements on the page will be center-aligned, with a red text color:
The CSS id Selector
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is used to select one unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of the element.
Example
The CSS rule below will be applied to the HTML element with
Note: An id name cannot start with a number!
The CSS class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
Example
In this example all HTML elements with will be red and center-aligned:
You can also specify that only specific HTML elements should be affected by a class.
Example
In this example only
elements with will be red and center-aligned:
HTML elements can also refer to more than one class.
Example
In this example the
element will be styled according to and to
This paragraph refers to two classes.
Note: A class name cannot start with a number!
The CSS Universal Selector
The universal selector (*) selects all HTML elements on the page.
Example
The CSS rule below will affect every HTML element on the page:
The CSS Grouping Selector
The grouping selector selects all the HTML elements with the same style definitions.
Look at the following CSS code (the h1, h2, and p elements have the same style definitions):
h2 text-align: center;
color: red;
>
p text-align: center;
color: red;
>
It will be better to group the selectors, to minimize the code.
To group selectors, separate each selector with a comma.
Example
In this example we have grouped the selectors from the code above:
All CSS Simple Selectors
Selector | Example | Example description |
---|---|---|
#id | #firstname | Selects the element with > |
.class | .intro | Selects all elements with > |
element.class | p.intro | Selects only elements with > |
* | * | Selects all elements |
element | p | Selects all elements |
element,element. | div, p | Selects all elements and all elements |