В CSS селекторы используются для стилизации HTML элементов на web-странице. Существует широкий выбор CSS селекторов, позволяющий максимально точно отбирать элементы для стилизации. В этой статье и её подстатьях мы рассмотрим разные типы в мельчайших подробностях и увидим как они работают.
Необходимые условия: | Базовая компьютерная грамотность, основное программное обеспечение, понимание работы с файлами, базовые знания HTML (смотрите Введение в HTML), и представление о том, как работает CSS (смотрите Первые шаги в CSS.) |
---|---|
Цель: | Узнать, как в деталях работают CSS селекторы. |
Что такое селекторы?
Вы уже встерчались с селекторами. Это выражения, которые говорят браузеру, к какому элементу HTML нужно применить те или иные свойства CSS определённые внутри блока объявления стиля.
Ранее вы встречали несколько разных селекторов и узнали, что существуют селекторы, которые по разному относятся к документу - например, используя элемент h1
или класс .special
.
В CSS селекторы определяются в спецификации CSS селекторов; как и другие части CSS нужно поддерживать их работу в браузерах. Большинство селекторов, которые вы встретите, определены в Спецификации селекторов 3 уровня, где вы сможете найти всю информацию о поддержке селекторов в браузерах.
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.
h1, .special {
color: blue;
}
White space is valid before or after the comma. You may also find the selectors more readable if each is on a new line.
h1,
.special {
color: blue;
}
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 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.
h1, ..special {
color: blue;
}
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 <h1>
.
h1 { }
It also includes selectors which target a class:
.box { }
or, an ID:
#unique { }
Attribute selectors
This group of selectors gives you different ways to select elements based on the presence of a certain attribute on an element:
a[title] { }
Or even make a selection based on the presence of an attribute with a particular value:
a[href="https://example.com"] { }
Pseudo-classes and pseudo-elements
This group of selectors includes pseudo-classes, which style certain states of an element. The :hover
pseudo-class for example selects an element only when it is being hovered over by the mouse pointer:
a:hover { }
It also includes pseudo-elements, which select a certain part of an element rather than the element itself. For example, ::first-line
always selects the first line of text inside an element (a <p>
in the below case), acting as if a <span>
was wrapped around the first formatted line and then selected.
p::first-line { }
Combinators
The final group of selectors combine other selectors in order to target elements within our documents. The following for example selects paragraphs that are direct children of <article>
elements using the child combinator (>
):
article > p { }
Next steps
You can take a look at the reference table of selectors below for direct links to the various types of selectors in this Learn section or on MDN in general, or continue on to start your journey by finding out about type, class, and ID selectors.
Reference table of selectors
The below table gives you an overview of the selectors you have available to use, along with links to the pages in this guide which will show you how to use each type of selector. I have also included a link to the MDN page for each selector where you can check browser support information. You can use this as a reference to come back to when you need to look up selectors later in the material, or as you experiment with CSS generally.
Selector | Example | Learn CSS tutorial |
---|---|---|
Type selector | h1 { } |
Type selectors |
Universal selector | * { } |
The universal selector |
Class selector | .box { } |
Class selectors |
id selector | #unique { } |
ID selectors |
Attribute selector | a[title] { } |
Attribute selectors |
Pseudo-class selectors | p:first-child { } |
Pseudo-classes |
Pseudo-element selectors | p::first-line { } |
Pseudo-elements |
Descendant combinator | article p |
Descendant combinator |
Child combinator | article > p |
Child combinator |
Adjacent sibling combinator | h1 + p |
Adjacent sibling |
General sibling combinator | h1 ~ p |
General sibling |