Css scope что это

An introduction to @scope in CSS

In January 2019 I raised an issue in the W3C CSS GitHub titled Please bring back scoped styles. There had once been a scoped HTML attribute but it got deprecated. It’s been replaced by @scope in CSS. Browser support is still forthcoming. It’s due to land in Chrome 117. Safari has a positive position on the specification. There are two selling points of @scope : styling based on proximity and setting a lower boundary for a selector.

Style based on proximity

Rather than just relying on source order and specificity, we now have the option to override styles based on proximity. Guess what color the button will be in the following examples:

@scope (.blue)  button   background-color: blue;  > > @scope (.green)  button   background-color: green;  > > @scope (.red)  button   background-color: red;  > >
div class="red">  div class="green">  div class="blue">  button>Clickbutton>  div>  div> div>
div class="blue">  div class="green">  div class="red">  button>Clickbutton>  div>  div> div> 

Answer: just look to the nearest ancestor. In example 1 the button is blue. In example 2 the button is red. (If you are on Chrome Canary you can see the CodePen example). Let’s look at a real world use case. @scope solves a problem I encountered back when working at the British phone network giffgaff. We had what we called “themes” — not light and dark themes that changed according to user preferences, but rather classes for styling different sections of a page with a particular color scheme. To ensure enough color contrast for easy readability, the link text color was dark blue when on a light background and light blue on a dark background. This saved us having to put a class on every single link, which would be tedious and prone to inconsistency.

.theme-white   background-color: white;  color: black;  > .theme-white a   color: #00528a; > .theme-black   background-color: black;  color: white; > .theme-black a   color: #35adce; >

This worked well enough, but had one problem: nesting. CSS doesn’t look to the nearest HTML ancestor to know which style to apply — it just goes by the source order in your CSS file. Depending on the order in which you’ve defined your styles, if you nest a white section in a black section, or nest a black section in a white section, the link won’t be the correct color anymore. There was really no solution to this issue prior to @scope .

div class="theme-white">  a href="example.com">This link is the correct colora> div> div class="theme-black">  a href="example.com">This link is the correct colora>  div class="theme-white">  a href="example.com">This link is the wrong colora>  div> div>

See the Pen Nesting issue when relying on source order by Ollie Williams (@cssgrid) on CodePen. With @scope we can solve this issue:

.theme-white   background-color: white;  color: black;  > .theme-gray   background-color: #f5f5f5;  color: black;  > @scope (.theme-white, .theme-gray)  a   color: #00528a;  > > .theme-black   background-color: black;  color: white; > @scope (.theme-black)  a   color: #35adce;  > >

Now whenever a link is on a white or gray background it’ll be dark blue. Whenever it’s on black background it’ll be a brighter lighter blue. We could optionally rewrite the previous CSS to use the :scope pseudo-class which references the root of the current scope. In the following example :scope would select any element that has a .theme-black class.

@scope (.theme-black)  :scope   background-color: black;  color: white;  >  a   color: #35adce;  > >

:scope isn’t a new pseudo-class. Its been in browsers for years but was previously pretty pointless when used in a stylesheet because outside of a @scope block it always means the same as :root (which selects the root element of the document — the element).

Set a lower boundary for a selector

Sometimes you want to style a component without styling certain things that are nested inside of it. Miriam Suzanne, a co-author of the scope specification, appeared on the Syntax podcast a few years ago to talk about @scope: “A tabs component has all these holes wherever your putting content in the tab. You don’t want the tab component to style the content, you just want it to style the tabs… We have descendent selectors where you can say anything inside of tabs but that’s not what we want. We want anything inside of tabs until you get to tab content. We want to be able to set a lower boundary on that selector.” Let’s take a look at the syntax:

@scope (.component) to (.content)  p   color: red;  > >
div class="component">  p>In scope.p>  div class="content">  p>Out of scope.p>  div> div>

If you have a paragraph within .content , it won’t be selected (if you have a browser that supports @scope you can look at the CodePen example). A @scope can have as many “holes” as you want:

@scope (.component) to (.content, .slot, .child-component)  p   color: red;  > >

Источник

CSS :scope Pseudo Class

The CSS :scope pseudo-class represents elements that are a reference point for selectors.

The :scope is the same as :root since, at the moment, there is not a way to explicitly establish a scoped element.

Scope element is an element forming a context for a block of styles.

Version

Syntax

Example of the :scope selector:

html> html> head> title>Title of the document title> style> .container < margin: 40px auto; max-width: 700px; background-color: #eeeeee; padding: 20px; box-shadow: 0 0 4px rgba(0, 0, 0, 0.25); > section < padding: 30px; > :scope < background-color: #1c87c9; > style> head> body> h2>:scope selector example h2> div class="container"> section> p> Inside the scope. p> section> div> body> html>

Browser support

Practice Your Knowledge

Which statement is incorrect about CSS :scope pseudo class?

Scope element is an element forming a context for a block of styles. The :scope pseudo-class represents elements that are a reference point for selectors to suit against. There is no difference between :root and :scope pseudo classes

Источник

Знакомимся с @scope в CSS

Эта статья — перевод оригинальной статьи «An introduction to @scope in CSS».

Также я веду телеграм канал “Frontend по-флотски”, где рассказываю про интересные вещи из мира разработки интерфейсов.

Вступление

В январе 2019 года я поднял вопрос в W3C CSS GitHub под названием Please bring back scoped styles. Когда-то существовал атрибут HTML scoped, но он был устаревшим. В CSS он был заменен на @scope . Поддержка должна появиться в Chrome 117. Safari так же занимает положительную позицию по спецификации.

У @scope есть два преимущества: стилизация на основе близости и установка нижней границы для селектора.

Стилизация на основе близости

Вместо того чтобы полагаться на порядок и специфику источника, теперь у нас есть возможность переопределять стили на основе близости. Угадайте, какого цвета будет кнопка в следующих примерах:

@scope (.blue) < button < background-color: blue; >> @scope (.green) < button < background-color: green; >> @scope (.red) < button < background-color: red; >>

Ответ: просто посмотрите на ближайшего предка. В примере 1 кнопка синяя. В примере 2 кнопка красная. (Если вы находитесь в Chrome Canary, вы можете посмотреть пример CodePen).

Давайте рассмотрим реальный пример использования. @scope решает проблему, с которой я столкнулся, работая в британской телефонной сети giffgaff. У нас было то, что мы называли «темами» — не светлые и темные темы, которые менялись в зависимости от предпочтений пользователя, а скорее классы для стилизации различных разделов страницы с определенной цветовой схемой. Чтобы обеспечить достаточный цветовой контраст для легкой читаемости, цвет текста ссылки был темно-синим на светлом фоне и светло-синим на темном. Это избавило нас от необходимости устанавливать класс для каждой отдельной ссылки, что было бы утомительно и чревато непоследовательностью.

.theme-white < background-color: white; color: black; >.theme-white a < color: #00528a; >.theme-black < background-color: black; color: white; >.theme-black a

Это работало достаточно хорошо, но была одна проблема: вложенность. CSS не смотрит на ближайшего предка HTML, чтобы узнать, какой стиль применить — он просто ориентируется на исходный порядок в вашем CSS-файле. В зависимости от порядка, в котором вы определили стили, если вы вложите белую секцию в черную или черную секцию в белую, ссылка уже не будет иметь правильный цвет. До появления @scope решения этой проблемы не было.

 
This link is the correct color
This link is the correct color
This link is the wrong color

С помощью @scope мы можем решить эту проблему:

.theme-white < background-color: white; color: black; >.theme-gray < background-color: #f5f5f5; color: black; >@scope (.theme-white, .theme-gray) < a < color: #00528a; >> .theme-black < background-color: black; color: white; >@scope (.theme-black) < a < color: #35adce; >>

Теперь, когда ссылка находится на белом или сером фоне, она будет темно-синей. Если ссылка находится на черном фоне, она будет светло-голубой.

По желанию мы можем переписать предыдущий CSS, чтобы использовать псевдокласс :scope , который ссылается на корень текущей области видимости. В следующем примере :scope будет выбирать любой элемент, имеющий класс .theme-black .

:scope не является новым псевдоклассом. Он используется в браузерах уже много лет, но раньше был довольно бессмысленным при использовании в CSS, потому что вне блока @scope он всегда означал то же самое, что и :root (который выбирает корневой элемент документа — элемент ).

Установка нижней границы для селектора

Иногда вы хотите стилизовать компонент без стилизации определенных вещей, которые вложены в него.

Мириам Сюзанн, соавтор спецификации scope, несколько лет назад выступила на подкасте Syntax, чтобы рассказать о @scope : «Компонент табов имеет все эти дыры, куда бы вы ни поместили содержимое вкладки. Вы не хотите, чтобы компонент вкладок стилизовал содержимое, вы просто хотите, чтобы он стилизовал вкладки. У нас есть селектор потомков, где вы можете указать что угодно внутри вкладок, но это не то, что нам нужно. Мы хотим, чтобы внутри вкладок было все, что угодно, пока вы не доберетесь до содержимого вкладки. Мы хотим иметь возможность установить нижнюю границу для этого селектора».

Давайте посмотрим на синтаксис:

@scope (.component) to (.content) < p < color: red; >>

Второй селектор устанавливает нижнюю границу — т.е. остановка стилизации с этой точки.

Если у вас есть параграф внутри .content , он не будет выбран (если у вас есть браузер, поддерживающий scope, вы можете посмотреть пример CodePen).

В @scope может быть столько «дыр», сколько вы захотите:

@scope (.component) to (.content, .slot, .child-component) < p < color: red; >>

Источник

:scope

The :scope CSS pseudo-class represents elements that are a reference point, or scope, for selectors to match against.

/* Selects a scoped element */ :scope  background-color: lime; > 

When used in a stylesheet, :scope is the same as :root , as there is currently no way to explicitly establish a scoped element. When used from a DOM API, such as querySelector() , querySelectorAll() , matches() , or Element.closest() , :scope matches the element on which the method was called.

Syntax

Examples

Identity match

This example demonstrates using the :scope pseudo-class with the Element.matches() method to match the element on which it’s called. In this example, if :scope is supported, and the paragraph is within the :root ‘s scope, text is displayed in the placeholder «output» paragraph.

JavaScript

const paragraph = document.getElementById("para"); const output = document.getElementById("output"); if (paragraph.matches(":scope"))  output.textContent = "The first paragraph is its own scope, as expected!"; > 

HTML

p id="para"> This is a paragraph. It is not an interesting paragraph. Sorry about that. p> p id="output">p> 

Result

Direct children

A situation where the :scope pseudo-class proves to be useful is when you need to get a direct descendant of an already retrieved Element .

JavaScript

const context = document.getElementById("context"); const selected = context.querySelectorAll(":scope > div"); document.getElementById("results").innerHTML = Array.prototype.map .call(selected, (element) => `#$element.getAttribute("id")>`) .join(", "); 

HTML

div id="context"> div id="element-1"> div id="element-1.1">div> div id="element-1.2">div> div> div id="element-2"> div id="element-2.1">div> div> div> p> Selected elements ids : span id="results">span> p> 

Result

The scope of context is the element with the id of context . The selected elements are the div elements that are direct children of that context, element-1 and element-2 , but not their descendants.

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 10, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Читайте также:  Svg icon background css
Оцените статью