Css selectors tag with class

Class selectors

The CSS class selector matches elements based on the contents of their class attribute.

Syntax

.class_name  style properties > 

Note that this is equivalent to the following attribute selector :

[class~=class_name]  style properties > 

Examples

CSS

.red  color: #f33; > .yellow-bg  background: #ffa; > .fancy  font-weight: bold; text-shadow: 4px 4px 3px #77f; > 

HTML

p class="red">This paragraph has red text.p> p class="red yellow-bg"> This paragraph has red text and a yellow background. p> p class="red fancy">This paragraph has red text and "fancy" styling.p> p>This is just a regular paragraph.p> 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 18, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

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.

Источник

Читайте также:  Python compare lists element by element
Оцените статью