search
HomeWeb Front-endCSS TutorialStyling in the Shadow DOM With CSS Shadow Parts 

Styling in the Shadow DOM With CSS Shadow Parts

Safari 13.1 introduced support for CSS Shadow Parts, which means that the ::part() selector is now supported by Chrome, Edge, Opera, Safari, and Firefox. This article will explore its uses and first review the packaging features of Shadow DOM.

Advantages of Shadow DOM Packaging

At giffgaff, we have a large amount of CSS code written by different people in many different ways. Let's see what problems this may bring.

Naming conflict

Class name conflicts are prone to occur in CSS. A developer may create a class name called .price . Another developer (and maybe even the same person) may use the same class name without knowing it.

CSS will not prompt any errors. Now any HTML element with this class will receive styles for two completely different things.

Shadow DOM resolves this issue. CSS-in-JS libraries like Emotion and styled-components also solve this problem in different ways by generating random class names such as .bwzfXH . This certainly helps avoid conflict! However, CSS-in-JS does not prevent anyone from breaking your components in other ways. For example……

Basic Styles and CSS Reset

HTML element selectors can be used (e.g.<button></button> and<div> ) Apply styles. These styles may break the component. Shadow DOM is the only mechanism that provides (almost) fully encapsulated-you can rest assured that your components will look consistent even in a messy <code>!important code base, because each component is encapsulated.

 /* This will not affect the buttons inside the Shadow DOM*/
button { background-color: lime !important; }

I don't think it's a good practice to style the element this way, but it does happen. Even if this happens, these styles do not affect the Shadow DOM.

It is worth noting that inheritable styles like color, font, and line height are still inherited in Shadow DOM. To prevent this, use all: initial or preferably all: revert after the browser supports better.

Let's look at a common example of CSS applied directly to HTML elements. Consider Eric Meyer's reset code:

 html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small strike strong sub sup tt var
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embedded,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
}

What happens if the component we are using uses the default margins and padding values ​​for the user agent? This reset may cause it to look corrupted, as these default values ​​are actually cleared.

Shadow DOM is a way to avoid these problems. Shadow DOM enables us to be fully convinced that the component will render as expected, no matter which code base it ends up in. Again, no code that is used only for components will inadvertently affect anything else—all without the cumbersome class naming conventions. Shadow DOM provides an encapsulation level that cannot be achieved in other ways.

The packaging is great, but we also want our components to be themed and customizable. ::part selector makes this much easier.

Style Shadow DOM with ::part()

So far, the only way CSS can modify custom element styles from outside Shadow DOM is to use CSS custom properties. In a strict design system, you only want to allow limited changes, which may be ideal. If you want your component to be more general, it can create problems. You need to use custom properties to define each CSS attribute you want to provide for style. It just sounds very complicated.

If we want to style components in different ways based on pseudo-classes (such as :hover ), the situation will be further complicated. Basically, we end up with a lot of custom properties. Let's look at an example from Ionic (a set of open source web components). Take a look at all the custom properties defined on the Ionic button component.

Feel free to check it out.

I counted 23 custom properties. Needless to say, this is far from ideal.

Here is an example of using ::part() to style elements.

In this example, I just changed the color, border and background color properties, but I can use any property I want without being limited by the custom properties that have been defined. Note that I can also use pseudo-classes such as :hover and :focus to style the different states of the component.

In this button example, the entire component is exposed for style setting, but if your web component contains multiple HTML elements, you can expose only selected parts of the component to this style setting - hence the name ::part . This prevents the component's users from styling any arbitrary elements within the Shadow tree. Component authors are responsible for revealing the components that they explicitly want to disclose. Other parts of the component can maintain visual consistency or use custom properties to achieve less customizability.

So, how do we set this for our components? Let's see how to use ::part to make certain elements of a web component styling. All we do is add a part property to the element we want to expose.

<div part="box"> ...</div>
<button>Click me</button>

In this example, div can be customized using the full CSS scope—any CSS attribute can be changed. But the button is locked – no one can change its visual effects except the component author.

Just as HTML elements can have multiple class names, one element can also have multiple part names:

<div part="box thing"> ...</div>

This is what we get with ::part : By exposing the "part" of the element, we can provide some flexibility on how to use web components while protecting them in other areas. Whether it’s your design system, component library, or anything else, the fact that CSS Shadow Parts is becoming mainstream provides us with another exciting tool.

The above is the detailed content of Styling in the Shadow DOM With CSS Shadow Parts . For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Iterating a React Design with Styled ComponentsIterating a React Design with Styled ComponentsApr 21, 2025 am 11:29 AM

In a perfect world, our projects would have unlimited resources and time. Our teams would begin coding with well thought out and highly refined UX designs.

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!Oh, the Many Ways to Make Triangular Breadcrumb Ribbons!Apr 21, 2025 am 11:26 AM

Oh, the Many Ways to Make Triangular Breadcrumb Ribbons

SVG Properties in CSS GuideSVG Properties in CSS GuideApr 21, 2025 am 11:21 AM

SVG has its own set of elements, attributes and properties to the extent that inline SVG code can get long and complex. By leveraging CSS and some of the forthcoming features of the SVG 2 specification, we can reduce that code for cleaner markup.

A Few Functional Uses for Intersection Observer to Know When an Element is in ViewA Few Functional Uses for Intersection Observer to Know When an Element is in ViewApr 21, 2025 am 11:19 AM

You might not know this, but JavaScript has stealthily accumulated quite a number of observers in recent times, and Intersection Observer is a part of that

Revisting prefers-reduced-motionRevisting prefers-reduced-motionApr 21, 2025 am 11:18 AM

We may not need to throw out all CSS animations. Remember, it’s prefers-reduced-motion, not prefers-no-motion.

How to Get a Progressive Web App into the Google Play StoreHow to Get a Progressive Web App into the Google Play StoreApr 21, 2025 am 11:10 AM

PWA (Progressive Web Apps) have been with us for some time now. Yet, each time I try explaining it to clients, the same question pops up: "Will my users be

The Simplest Ways to Handle HTML IncludesThe Simplest Ways to Handle HTML IncludesApr 21, 2025 am 11:09 AM

It's extremely surprising to me that HTML has never had any way to include other HTML files within it. Nor does there seem to be anything on the horizon that

Change Color of SVG on HoverChange Color of SVG on HoverApr 21, 2025 am 11:04 AM

There are a lot of different ways to use SVG. Depending on which way, the tactic for recoloring that SVG in different states or conditions — :hover,

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software