- 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
- Type, class, and ID selectors
- Type selectors
- The universal selector
- Using the universal selector to make your selectors easier to read
- Class selectors
- Targeting classes on particular elements
- Target an element if it has more than one class applied
- ID selectors
- Summary
- Found a content problem with this page?
- CSS-селекторы
- Базовые селекторы
- Комбинаторы
- Псевдо
- Версии CSS
- Смотрите также
- Found a content problem with this page?
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 |
Type, class, and ID selectors
In this lesson, we examine some of the simplest selectors, which you will probably use most frequently in your 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 about the different CSS selectors we can use to apply CSS to a document. |
Type selectors
A type selector is sometimes referred to as a tag name selector or element selector because it selects an HTML tag/element in your document. In the example below, we have used the span , em and strong selectors.
Try adding a CSS rule to select the element and change its color to blue.
The universal selector
The universal selector is indicated by an asterisk ( * ). It selects everything in the document (or inside the parent element if it is being chained together with another element and a descendant combinator). In the following example, we use the universal selector to remove the margins on all elements. Instead of the default styling added by the browser — which spaces out headings and paragraphs with margins — everything is close together.
This kind of behavior can sometimes be seen in «reset stylesheets», which strip out all of the browser styling. Since the universal selector makes global changes, we use it for very specific situations, such as the one described below.
Using the universal selector to make your selectors easier to read
One use of the universal selector is to make selectors easier to read and more obvious in terms of what they are doing. For example, if we wanted to select any descendant elements of an element that are the first child of their parent, including direct children, and make them bold, we could use the :first-child pseudo-class. We will learn more about this in the lesson on pseudo-classes and pseudo-elements, as a descendant selector along with the element selector:
article :first-child font-weight: bold; >
However, this selector could be confused with article:first-child , which will select any element that is the first child of another element.
To avoid this confusion, we can add the universal selector to the :first-child pseudo-class, so it is more obvious what the selector is doing. It is selecting any element which is the first-child of an element, or the first-child of any descendant element of :
article *:first-child font-weight: bold; >
Although both do the same thing, the readability is significantly improved.
Class selectors
The class selector starts with a dot ( . ) character. It will select everything in the document with that class applied to it. In the live example below we have created a class called highlight , and have applied it to several places in my document. All of the elements that have the class applied are highlighted.
Targeting classes on particular elements
You can create a selector that will target specific elements with the class applied. In this next example, we will highlight a with a class of highlight differently to an heading with a class of highlight . We do this by using the type selector for the element we want to target, with the class appended using a dot, with no white space in between.
This approach reduces the scope of a rule. The rule will only apply to that particular element and class combination. You would need to add another selector if you decided the rule should apply to other elements too.
Target an element if it has more than one class applied
You can apply multiple classes to an element and target them individually, or only select the element when all of the classes in the selector are present. This can be helpful when building up components that can be combined in different ways on your site.
In the example below, we have a that contains a note. The grey border is applied when the box has a class of notebox . If it also has a class of warning or danger , we change the border-color .
We can tell the browser that we only want to match the element if it has two classes applied by chaining them together with no white space between them. You’ll see that the last doesn’t get any styling applied, as it only has the danger class; it needs notebox as well to get anything applied.
ID selectors
An ID selector begins with a # rather than a dot character, but is used in the same way as a class selector. However, an ID can be used only once per page, and elements can only have a single id value applied to them. It can select an element that has the id set on it, and you can precede the ID with a type selector to only target the element if both the element and ID match. You can see both of these uses in the following example:
Warning: Using the same ID multiple times in a document may appear to work for styling purposes, but don’t do this. It results in invalid code, and will cause strange behavior in many places.
Note: As we learned in the lesson on specificity, an ID has high specificity. It will overrule most other selectors. In most cases, it is preferable to add a class to an element instead of an ID. However, if using the ID is the only way to target the element — perhaps because you do not have access to the markup and cannot edit it — this will work.
Summary
That wraps up Type, class, and ID selectors. We’ll continue exploring selectors by looking at attribute selectors.
Found a content problem with this page?
This page was last modified on Jun 30, 2023 by MDN contributors.
Your blueprint for a better internet.
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.