- 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 selector to match class with number greater than
- CSS Style
- HTML Body
- Related
- CSS selector to match class with number greater than
- CSS Style
- HTML Body
- Related
- 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 |
CSS selector to match class with number greater than
The following tutorial shows you how to use CSS to do «CSS selector to match class with number greater than».
CSS Style
The CSS style to do «CSS selector to match class with number greater than» is
div < background:blue; border:1px solid #fff; color:#fff; height:20px; width:20px; > [class*='x-ios-']:not(.x-ios-3):not(.x-ios-4):not(.x-ios-5):not(.x-ios-6) < background:red; >
HTML Body
body> div >"x-ios-3"> 3!-- w w w. d em o 2 s . c o m--> div >"x-ios-4"> 4 div >"x-ios-5"> 5 div >"x-ios-6"> 6 div >"x-ios-7"> 7 div >"x-ios-8"> 8 div >"x-ios-9"> 9
The following iframe shows the result. You can view the full source code and open it in another tab.
html> head> meta name="viewport" content="width=device-width, initial-scale=1"> style id="compiled-css" type="text/css"> div !-- w w w . d e m o 2 s . c o m --> background: blue; border: 1px solid #fff; color: #fff; height: 20px; width: 20px; > [class*='x-ios-']:not(.x-ios-3):not(.x-ios-4):not(.x-ios-5):not(.x-ios-6) < /* ios >= 7 */ background: red; > body> div >"x-ios-3">3 div >"x-ios-4">4 div >"x-ios-5">5 div >"x-ios-6">6 div >"x-ios-7">7 div >"x-ios-8">8 div >"x-ios-9">9
Related
- CSS selector to find the first tbody
- CSS selector to hide first of a set
- CSS selector to hide first of a set (Demo 2)
- CSS selector to match class with number greater than
- CSS Selector to match input not contained in a div with specific class
- CSS selector to select all elements in Page where specific element exists
- CSS selector to select all elements in Page where specific element exists (Demo 2)
demo2s.com | Email: | Demo Source and Support. All rights reserved.
CSS selector to match class with number greater than
The following tutorial shows you how to use CSS to do «CSS selector to match class with number greater than».
CSS Style
The CSS style to do «CSS selector to match class with number greater than» is
div < background:blue; border:1px solid #fff; color:#fff; height:20px; width:20px; > [class*='x-ios-']:not(.x-ios-3):not(.x-ios-4):not(.x-ios-5):not(.x-ios-6) < background:red; >
HTML Body
body> div >"x-ios-3"> 3!-- w w w. d em o 2 s . c o m--> div >"x-ios-4"> 4 div >"x-ios-5"> 5 div >"x-ios-6"> 6 div >"x-ios-7"> 7 div >"x-ios-8"> 8 div >"x-ios-9"> 9
The following iframe shows the result. You can view the full source code and open it in another tab.
html> head> meta name="viewport" content="width=device-width, initial-scale=1"> style id="compiled-css" type="text/css"> div !-- w w w . d e m o 2 s . c o m --> background: blue; border: 1px solid #fff; color: #fff; height: 20px; width: 20px; > [class*='x-ios-']:not(.x-ios-3):not(.x-ios-4):not(.x-ios-5):not(.x-ios-6) < /* ios >= 7 */ background: red; > body> div >"x-ios-3">3 div >"x-ios-4">4 div >"x-ios-5">5 div >"x-ios-6">6 div >"x-ios-7">7 div >"x-ios-8">8 div >"x-ios-9">9
Related
- CSS selector to find the first tbody
- CSS selector to hide first of a set
- CSS selector to hide first of a set (Demo 2)
- CSS selector to match class with number greater than
- CSS Selector to match input not contained in a div with specific class
- CSS selector to select all elements in Page where specific element exists
- CSS selector to select all elements in Page where specific element exists (Demo 2)
demo2s.com | Email: | Demo Source and Support. All rights reserved.
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.