Css syntax and selectors

CSS Syntax and Selectors

CSS Selector can be divided into 5 categories: Simple Selector: It is used to select the HTML elements based on their element name, id, attributes, etc. The Simple Selector can be categorized in 3 ways: CSS element selector : The element selector in CSS is used to select HTML elements that are required to be styled.

CSS Syntax

A CSS rule consists of a selector and a declaration block.

CSS Syntax

The selector points to the HTML element you want to style.

The declaration block contains one or more declarations separated by semicolons.

Each declaration includes a CSS property name and a value, separated by a colon.

Multiple CSS declarations are separated with semicolons, and declaration blocks are surrounded by curly braces.

Example

In this example all

elements will be center-aligned, with a red text color:

Example Explained
  • p is a selector in CSS (it points to the HTML element you want to style:

    ).

  • color is a property, and red is the property value
  • text-align is a property, and center is the property value

You will learn much more about CSS selectors and CSS properties in the next chapters!

Which is the correct syntax to make all elements bold?, Which is the correct syntax to make all

elements bold? Which property do you need to change the background color? How can you add a comment in a CSS …

What is the correct css syntax for making all the p

In this video session, we will learn -1. Correct CSS syntax for making all the p elements bold .2. How to use class for applying style to p ?3. How to apply st

CSS Syntax and Selectors

A CSS Syntax rule consists of a selector, property, and its value. The selector points to the HTML element where CSS style is to be applied. The CSS property is separated by semicolons. It is a combination of selector name followed by the property: value pair that is defined for the specific selector.

For instance, we have declared a heading tag(h1) along with having assigned some property: value pair that is used to style the heading tag. Here, h1 is selector, is a declaration block & it can contain one or more declarations separated by semicolons, color: green; is a property: value pair that is applied to the HTML element in order to style them.

Every declaration has a CSS property name and a value, separated by a colon & is surrounded by curly braces. For declaring the multiple CSS properties , it can be separated by the semicolon.

Example: This example illustrates the use of CSS Syntax for the styling of HTML elements.

HTML

A CSS Selectors are used to selecting HTML elements based on their element name, id, attributes, etc. It can select one or more elements simultaneously.

CSS Selector can be divided into 5 categories:

  • Simple Selector: It is used to select the HTML elements based on their element name, id, attributes, etc.
  • Combinators Selector: It is used for explaining the relationship between two selectors.’
  • Pseudo-classes Selector : It is used to define the special state of an element.
  • Pseudo Elements Selector : It is a keyword added to a selector that lets you style a specific part of the selected elements .
  • Attribute Selector Selector: It is used to select an element with some specific attribute or attribute value.

We will focus ourselves to the Simple Selector & also understand its implementation through the examples.

The Simple Selector can be categorized in 3 ways:

CSS element selector : The element selector in CSS is used to select HTML elements that are required to be styled. In a selector declaration, there is the name of the HTML element, and the CSS properties which are to be applied to that element are written inside the brackets <>.

Example: This example illustrates the use of the element selector for selecting the HTML elements by their element name & style them.

Источник

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

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

Источник

Читайте также:  Page Title
Оцените статью