🌐 Introduction
In modern web development, especially when working with Web Components, developers need a way to create self-contained, reusable components. Each component should have its own HTML, CSS, and JavaScript, without affecting the rest of the page. This is where Shadow DOM comes in. It provides encapsulation, meaning the code inside a component stays private and doesn’t interfere with the rest of the document.
🧩 What Is Shadow DOM?
Shadow DOM is a web standard that encapsulates style and markup inside web components. It is part of the Web Components standard, which also includes Custom Elements, HTML Templates, and HTML Imports.
When you use Shadow DOM, you attach a hidden, isolated DOM tree to a host element. The element to which it is attached is called the Shadow Host, and the hidden DOM structure is called the Shadow Tree. This shadow tree can contain its own HTML, CSS, and logic without leaking into the main DOM.
👉 Example: A video player on a webpage uses Shadow DOM to isolate its controls (play, pause, volume). The styles and scripts for these controls don’t interfere with the rest of the page.
⚙️ How Shadow DOM Works
Shadow DOM works by attaching a hidden DOM tree (called the Shadow Tree) to a regular DOM element (known as the Shadow Host). This allows developers to encapsulate styles and markup so that they don’t interfere with the rest of the page.
When a Shadow DOM is created, it works independently of the main DOM. Styles defined inside it will only apply to its elements, and JavaScript interactions are scoped to that specific component. This makes components reusable, predictable, and safe from global CSS conflicts.
Practical Example of Shadow DOM
Let’s look at a simple example of how to use Shadow DOM in a custom element. Here, we’ll create a reusable <custom-button> component with its own isolated styles and behavior:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Shadow DOM Example</title>
</head>
<body>
<!-- Using the custom button component -->
<custom-button></custom-button>
<script>
class CustomButton extends HTMLElement {
constructor() {
super();
// Attach Shadow DOM to the element
const shadow = this.attachShadow({ mode: "open" });
// Create a button element
const button = document.createElement("button");
button.textContent = "Click Me";
// Define styles scoped only to this component
const style = document.createElement("style");
style.textContent = `
button {
background: blue;
color: white;
padding: 10px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: darkblue;
}
`;
// Append style and button to shadow DOM
shadow.appendChild(style);
shadow.appendChild(button);
}
}
// Register the custom element
customElements.define("custom-button", CustomButton);
</script>
</body>
</html>
In this example:
Join the conversation! Your thoughts help the community grow.