From 6db87e35340b42af3ac38c33eb9acc5a7d970023 Mon Sep 17 00:00:00 2001 From: Ajay Dhangar Date: Mon, 1 Dec 2025 09:19:59 +0530 Subject: [PATCH] done advanced features --- docs/css/advanced-features/cascade-layers.mdx | 161 ++++++++++++++++- docs/css/advanced-features/css-functions.mdx | 115 ++++++++++++- docs/css/advanced-features/css-layers.mdx | 144 +++++++++++++++- docs/css/advanced-features/css-variables.mdx | 162 +++++++++++++++++- docs/css/advanced-features/inheritance.mdx | 132 +++++++++++++- docs/css/advanced-features/shadow-dom.mdx | 137 ++++++++++++++- docs/css/advanced-features/specificity.mdx | 105 +++++++++++- 7 files changed, 949 insertions(+), 7 deletions(-) diff --git a/docs/css/advanced-features/cascade-layers.mdx b/docs/css/advanced-features/cascade-layers.mdx index e345ed2..b4d6ee3 100644 --- a/docs/css/advanced-features/cascade-layers.mdx +++ b/docs/css/advanced-features/cascade-layers.mdx @@ -1 +1,160 @@ - \ No newline at end of file +--- +title: "CSS Cascade Layers (@layer)" +description: "Learn how to use the @layer rule to organize CSS styles into distinct layers, gaining control over the cascade and solving specificity conflicts in complex stylesheets." +keywords: [CSS layers, '@layer', cascade control, specificity, CSS organization, component layers, framework layers, layer precedence, unlayered styles] +tags: [CSS layers, '@layer', cascade control, specificity, CSS organization, component layers, framework layers, layer precedence, unlayered styles] +sidebar_label: Cascade Layers +--- + +CSS Cascade Layers, introduced by the **`@layer`** at-rule, provide a powerful mechanism for organizing CSS and controlling the **cascade** more predictably. They solve a long-standing problem in large-scale CSS projects: how to manage specificity conflicts between different sources of styles (e.g., framework, base, components, and utilities). + +**The Core Concept:** Styles within a higher-priority layer will *always* win over styles in a lower-priority layer, **regardless of the selector's specificity** within those layers. + + +
+ +## 1. The Cascade Layer Order + +The final result of a style depends on a fixed order of precedence. Cascade Layers slot into the standard cascade but allow you to define a sub-order for your own styles. + +**The Key Layer Precedence Rule:** + +* **Earlier layers have lower priority (less important).** +* **Later layers have higher priority (more important).** + +This means a simple selector in a late-defined layer can override a highly specific selector in an early-defined layer. + +### Order of Author Styles (Lowest to Highest Priority) + +1. **Styles within the first defined `@layer`** (e.g., `reset`). +2. **Styles within later defined `@layer`s** (e.g., `utilities`). +3. **Unlayered Styles** (CSS not wrapped in any `@layer` block). +4. **Author `!important` declarations.** + + +## 2. Defining and Ordering Layers + +You must define the order of your layers using a single `@layer` statement, typically placed at the very top of your CSS file. + +### 2.1. Defining the Order + +```css +/* 1. Define the layer order (Lowest to Highest Precedence) */ +@layer reset, framework, base, components, utilities; +``` + +In this setup: `reset` has the lowest priority, and `utilities` has the highest priority among the layers. + + +
+ +### 2.2. The Specificity vs. Layer Rule + +This is the most critical concept to understand: + +> **Layer Order Trumps Specificity:** The specificity of a selector only matters *within* its own layer. Once two properties conflict across two different layers, the layer order determines the winner, ignoring specificity. + +:::tip Layer Wins +Consider two rules: +1. `.box` (`specificity: 0,1,0`) in the `base` layer. +2. `#box-id` (`specificity: 1,0,0`) in the `utilities` layer. + +If `utilities` is defined *after* `base`, the simple `.box` utility will override the highly specific `#box-id` selector, because the `utilities` layer has higher precedence. This is how layers flip the cascade. +::: + +### 2.3. Creating Layer Blocks + +You then wrap your styles in named `@layer` blocks. You can define layers across multiple files or multiple blocks in the same file; the browser will stitch them together based on the initial ordering statement. + +```css title="styles.css" +/* -- 1. Reset Layer (Lowest Priority) -- */ +@layer reset { + /* This universal selector style is easily overridden by any other layer. */ + * { + box-sizing: border-box; + } +} + +/* -- 2. Components Layer (Mid Priority) -- */ +@layer components { + /* Specific component style */ + .card-title { + color: var(--theme-color); + } +} +``` + +## 3. Unlayered Styles (The Override) + +Styles that are **not** included in any `@layer` block are referred to as **unlayered styles**. + +Unlayered styles always have a higher precedence than **all** layered styles, regardless of their position in the file or the layer order. + +:::warning Unlayered Priority +Use unlayered styles sparingly, typically only for final, non-negotiable overrides or small third-party snippets where integrating them into a layer is impractical. Relying heavily on unlayered styles defeats the purpose of managing the cascade with layers. The goal should be to make 99% of your styles layered. +::: + +```css title="styles.css" +/* This style is NOT wrapped in @layer. Specificity: 0,1,0 */ +.final-override { + /* This will win over ALL layered styles, even if the selector is simpler. */ + background-color: green; +} + +/* This is a layered style that loses to the unlayered style above. Specificity: 0,1,0 */ +@layer utilities { + .final-override { + background-color: red; + } +} +``` + + +
+ +## 4. Layer Organization and Naming + +A common layer strategy is to move from the least specific, broadest styles to the most specific, overriding styles. + +| Layer Name | Typical Content | Priority | Role | +| :--- | :--- | :--- | :--- | +| **`reset`** | CSS resets (e.g., normalize.css), global box-sizing. | Lowest | Provides a clean slate. | +| **`framework`** | Third-party libraries (Tailwind base, Bootstrap). | Low | Imports external defaults. | +| **`base`** | Element selectors (`h1`, `p`, `a`), custom fonts, root variables. | Mid-Low | Defines project defaults. | +| **`components`** | Reusable, complex class selectors (e.g., `.modal`, `.card`). | Mid-High | Defines component structure. | +| **`utilities`** | Single-purpose, overriding classes (e.g., `.u-hidden`, `.u-text-red`). | Highest | Ensures utility classes always win. | + +### Nested and Imported Layers + +Layers can be nested, and styles can be imported directly into a layer, making framework integration seamless. + +:::info Layer Nesting +Nesting layers helps organize large component libraries (e.g., separating forms from navigation). + +```css title="styles.css" +/* Initial layer declaration must include the top level: */ +@layer framework, components; + +/* Importing an external file into the 'framework' layer */ +@import url('bootstrap.css') layer(framework); + +/* Defining a nested layer within components */ +@layer components.forms { + /* Styles for form components */ + .input-field { border-color: gray; } +} +``` +Styles in `components.forms` have the same precedence as `components` styles. +::: + + +
+ +## Interactive CSS Layers Demo + +This example demonstrates the precedence: The `utility` layer is defined later than the `component` layer, so the utility's style always wins. The `unlayered` style wins over both. + + \ No newline at end of file diff --git a/docs/css/advanced-features/css-functions.mdx b/docs/css/advanced-features/css-functions.mdx index e345ed2..2b4cdab 100644 --- a/docs/css/advanced-features/css-functions.mdx +++ b/docs/css/advanced-features/css-functions.mdx @@ -1 +1,114 @@ - \ No newline at end of file +--- +title: "Advanced CSS Functions (calc, clamp, min, max)" +description: "Explore essential CSS functions like calc(), clamp(), min(), and max() for dynamic sizing, combining fixed and fluid units to create highly robust and mathematical layouts." +keywords: [CSS functions, calc, clamp, min, max, dynamic sizing, mathematical layouts, fluid typography, responsiveness] +tags: [CSS functions, calc, clamp, min, max, dynamic sizing, mathematical layouts, fluid typography, responsiveness] +sidebar_label: CSS Functions +--- + +CSS is no longer a static styling language. Modern CSS includes powerful functions that allow you to perform calculations and create dynamic, responsive values that adapt to the browser environment. + +The four most important functions for creating robust layouts are `calc()`, `clamp()`, `min()`, and `max()`. + + +
+ +## 1. `calc()`: Mathematical Calculations + +The `calc()` function allows you to perform basic arithmetic (addition, subtraction, multiplication, division) within CSS property values. + +Its primary benefit is the ability to mix different unit types (e.g., mixing fixed pixels with fluid percentages or viewport units). + +### 1.1. Syntax and Rules + +```css title="styles.css" +/* Example: 50% of the parent width minus a fixed 20px of padding */ +width: calc(50% - 20px); +``` + +**Crucial Rule for `calc()`:** + + * **Spaces are mandatory** around the `+` and `-` operators. `calc(50% - 20px)` is correct. `calc(50%-20px)` will break. + * Spaces are optional for `*` and `/`. + +### 1.2. Practical Use Cases + +| Use Case | Example | Description | +| :--- | :--- | :--- | +| **Gutter Management** | `width: calc(100% / 3 - 2rem);` | Calculates the width of three equal columns, subtracting necessary margin/gap space. | +| **Viewport Offset** | `height: calc(100vh - 80px);` | Sets an element height to the full viewport height minus a fixed header height. | +| **Variable Manipulation** | `padding: calc(var(--base-unit) * 1.5);` | Scales a CSS variable by a factor. | + + +
+ +## 2. `clamp()`: Bounding Fluid Values + +The `clamp()` function pins a value between a minimum and a maximum size. This is the cornerstone of modern, fluid typography. + +`clamp()` takes three arguments: **Minimum Value, Preferred (Fluid) Value, Maximum Value**. + +```css title="styles.css" +/* Example: Font size that scales between 16px and 24px based on viewport width +clamp( MIN, PREFERRED, MAX ) +``` + +### 2.1. Fluid Typography Example + +```css title="styles.css" +h1 { + /* Font size will never be smaller than 3rem, + never larger than 5rem, and will scale fluidly in between. */ + font-size: clamp(3rem, 2rem + 2vw, 5rem); +} +``` + + * If the result of `2rem + 2vw` is less than `3rem`, the browser uses `3rem`. + * If the result is greater than `5rem`, the browser uses `5rem`. + * Otherwise, the browser uses the fluid value. + +## 3. `min()` and `max()`: Setting Limits + +The `min()` and `max()` functions allow you to choose the smallest or largest value from a comma-separated list of expressions. This is excellent for creating resilient components that avoid common layout pitfalls. + +### 3.1. `min()`: Selecting the Smaller Value + +`min(value1, value2, ...)` chooses the smallest value. + +**Use Case: Preventing Element Overflow.** +Imagine you want a container to be $50\%$ of the screen width, but never wider than a fixed 800px. + +```css title="styles.css" +.container { + /* The width will be 50% OR 800px, whichever is smaller. + This effectively sets the max-width dynamically. */ + width: min(50vw, 800px); +} +``` + + +
+ +### 3.2. `max()`: Selecting the Larger Value + +`max(value1, value2, ...)` chooses the largest value. + +**Use Case: Ensuring Minimum Size.** +Imagine you want a sidebar to be 20% of the screen width, but it must be at least 250px wide to hold its content. + +```css title="styles.css" +.sidebar { + /* The width will be 20% OR 250px, whichever is larger. + This effectively sets the min-width dynamically. */ + width: max(20vw, 250px); +} +``` + +## Interactive CSS Functions Demo + +This example uses `calc()`, `min()`, and `max()` to demonstrate dynamic sizing in a layout. + + \ No newline at end of file diff --git a/docs/css/advanced-features/css-layers.mdx b/docs/css/advanced-features/css-layers.mdx index e345ed2..6a245ca 100644 --- a/docs/css/advanced-features/css-layers.mdx +++ b/docs/css/advanced-features/css-layers.mdx @@ -1 +1,143 @@ - \ No newline at end of file +--- +title: "CSS Layers (@layer)" +description: "Learn how to use the @layer rule to organize CSS styles into distinct layers, gaining control over the cascade and solving specificity conflicts in complex stylesheets." +keywords: [CSS layers, '@layer', cascade control, specificity, CSS organization, component layers, framework layers] +tags: [CSS layers, '@layer', cascade control, specificity, CSS organization, component layers, framework layers] +sidebar_label: CSS Layers +--- + +CSS Cascade Layers, introduced by the `@layer` at-rule, provide a powerful mechanism for organizing CSS and controlling the **cascade** more predictably. They solve a long-standing problem in large-scale CSS projects: how to manage specificity conflicts between different sources of styles (e.g., framework, base, components, and utilities). + +**The Core Concept:** Styles within a higher-priority layer will *always* win over styles in a lower-priority layer, **regardless of the selector's specificity** within those layers. + + +
+ +## 1. The Cascade Layer Order + +The final result of a style depends on the following order of precedence, from lowest to highest: + +1. **User Agent Styles** (Browser defaults) +2. **Author Styles** (Your written CSS) + * **Normal styles in the order they appear** (without `@layer`) + * **Styles within layers** (Layer order is custom, see below) +3. **User Styles** (`!important` rules) +4. **Author Styles** (`!important` rules) +5. **User Agent Styles** (`!important` rules) + +Within the "Styles within layers" category, the layer order is defined by you. + +### Layer Precedence Rule + +When using layers, the precedence is determined by the layer order defined at the top of your stylesheet: + + * **Earlier layers have lower priority.** + * **Later layers have higher priority.** + +**Crucially:** Styles outside any layer are treated as having the highest priority among all normal author styles. + +## 2. Defining and Ordering Layers + +You define the order of your layers using a single `@layer` statement at the top of your CSS file. + +### 2.1. Defining the Order + +```css title="styles.css" +/* 1. Define the layer order (Lowest to Highest Precedence) */ +@layer reset, framework, base, components, utilities; +``` + +Based on this order: + + * `reset` styles have the lowest priority. + * `utilities` styles have the highest priority. + + +
+ +### 2.2. Creating Layer Blocks + +You then wrap your styles in named `@layer` blocks. + +```css title="styles.css" +/* -- 1. Reset Layer (Lowest Priority) -- */ +@layer reset { + /* This style will lose to any style in a higher layer, even if the selector is less specific. */ + * { + margin: 0; + padding: 0; + } +} + +/* -- 2. Components Layer (Mid Priority) -- */ +@layer components { + /* Example: A component style */ + .button { + background-color: var(--theme-color); + padding: 10px 20px; + } +} + +/* -- 3. Utilities Layer (Highest Layer Priority) -- */ +@layer utilities { + /* This utility class will override .button's background, even though it's less specific */ + .u-red { + background-color: red; + } +} +``` + +If both `.button` and `.u-red` target the same property on the same element, the style from the `utilities` layer wins because `utilities` was defined *after* `components` in the initial `@layer` order. + + +
+ +## 3. Unlayered Styles (The Exception) + +Styles that are *not* included in any `@layer` block are considered **unlayered styles**. They have a higher precedence than **all** layered styles. + +This is a deliberate feature, ensuring that quick, necessary overrides or custom changes that don't belong in a specific layer can still win without resorting to `!important`. + +| Style Type | Priority (Highest to Lowest) | +| :--- | :--- | +| **`!important` (Author)** | Highest | +| **Unlayered Styles** | High (Wins over all layered styles) | +| **Layered Styles** | Mid (Order is determined by `@layer` definition) | +| **Normal Specificity** | Lowest (Standard specificity rules apply *within* a layer) | + +## 4. Practical Use Case: Framework Integration + +Layers are essential when combining external CSS (like a framework) with your custom styles. + +**Goal:** Ensure your custom component styles can easily override framework defaults without needing complex selectors. + +```css title="styles.css" +/* 1. Define the Order */ +/* Framework is low priority; components are high priority */ +@layer framework, components, utilities; + +/* 2. Import the Framework (e.g., a simple UI kit) */ +@import url('external-ui-framework.css') layer(framework); + +/* 3. Write Custom Styles */ +@layer components { + /* Even if .fw-btn-primary has high specificity in the framework, + this style will win because the 'components' layer is defined later. */ + .fw-btn-primary { + background-color: darkgreen; /* Your custom color wins */ + border-radius: 20px; + } +} +``` + + +
+ +## Interactive CSS Layers Demo + +This demo illustrates layer precedence: the `Utility` layer is defined later than the `Component` layer, so the Utility's background color always wins, despite the Component selector being equally specific. + + \ No newline at end of file diff --git a/docs/css/advanced-features/css-variables.mdx b/docs/css/advanced-features/css-variables.mdx index e345ed2..ae57eb5 100644 --- a/docs/css/advanced-features/css-variables.mdx +++ b/docs/css/advanced-features/css-variables.mdx @@ -1 +1,161 @@ - \ No newline at end of file +--- +title: "CSS Variables (Custom Properties)" +description: "Learn how to use CSS Custom Properties (Variables) to define reusable values for colors, fonts, spacing, and more, enabling easier maintenance and dynamic theming." +keywords: [CSS variables, custom properties, var function, scope, theming, cascading, maintenance] +tags: [CSS variables, custom properties, var function, scope, theming, cascading, maintenance] +sidebar_label: CSS Variables +--- + +CSS Variables, officially called **Custom Properties**, allow you to define reusable values (like colors, font sizes, or spacing amounts) in one place and reuse them throughout your stylesheets. + +They bring the efficiency of variables from programming languages directly into CSS, dramatically improving maintainability, consistency, and the ability to implement dynamic theming. + + +
+ +## 1. Defining and Using Variables + +### 1.1. Declaration + +Custom properties are declared with a name starting with two hyphens (`--`). + +### 1.2. Scope + +The scope defines where the variable can be accessed. + + * **Global Scope:** Declared on the `:root` pseudo-class (which is equivalent to the `` element). These variables are available everywhere in the document. + * **Local Scope:** Declared on a specific selector (e.g., `.card`). These variables are only available to that element and its descendants. + +### Example: Global and Local Variables + +```css title="styles.css" +/* Global Scope: Accessible everywhere */ +:root { + --primary-color: #3B82F6; /* Blue */ + --spacing-base: 1rem; +} + +/* Local Scope: Only accessible within .card and its children */ +.card { + --card-shadow: 0 4px 10px rgba(0, 0, 0, 0.1); + background-color: white; + border-radius: 8px; + padding: var(--spacing-base); + box-shadow: var(--card-shadow); +} +``` + +### 1.3. Usage (`var()` function) + +To retrieve the value of a Custom Property, you use the `var()` function. + +```css title="styles.css" +.button { + /* Use the global variable defined on :root */ + background-color: var(--primary-color); + + /* Use the global spacing variable */ + margin-top: var(--spacing-base); +} +``` + + +
+ +## 2. Fallbacks (Default Values) + +The `var()` function accepts an optional second argument, which acts as a fallback value. If the specified variable is not defined or is invalid, the browser will use the fallback instead. + +This is useful for local components where a variable might be optional. + +```css title="styles.css" +.title { + /* If --title-color is defined, use it. Otherwise, use black. */ + color: var(--title-color, black); +} +``` + +## 3. Benefits of Using Variables + +### A. Consistency and Maintenance (DRY Principle) + +Changing a single variable definition updates every instance of that value across your entire application. This is essential for maintaining a consistent design system (e.g., ensuring all buttons use the exact same primary color). + + +
+ +### B. Dynamic Theming (Dark Mode) + +Variables are the easiest way to implement dynamic themes like Dark Mode. You simply redefine the color variables inside a Media Query or a class selector. + +```css title="styles.css" +/* Base Light Theme Colors */ +:root { + --background-color: white; + --text-color: black; +} + +/* Dark Theme Override */ +@media (prefers-color-scheme: dark) { + :root { + --background-color: #1a1a1a; + --text-color: #f0f0f0; + } +} +``` + +Now, all elements that use `var(--background-color)` will automatically flip themes based on the user's OS preference. + +### C. Calculations + +You can use Custom Properties within the `calc()` function. + +```css title="styles.css" +:root { + --sidebar-width: 250px; +} + +.main-content { + /* Dynamically calculate the main content width */ + width: calc(100% - var(--sidebar-width) - 2rem); +} +``` + + +
+ +## 4. Interaction with JavaScript + +Unlike preprocessor variables (like Sass variables), CSS Custom Properties are part of the live DOM and can be read and written directly with JavaScript, enabling powerful dynamic interactions. + +### 4.1. Reading a Variable + +```javascript title="script.js" +// Get the value of the primary color on the root element +const root = document.documentElement; +const primaryColor = getComputedStyle(root).getPropertyValue('--primary-color'); +console.log(primaryColor); // Output: #3B82F6 +``` + +### 4.2. Setting a Variable + +You can update a variable on any element, and all dependent styles will update instantly. + +```javascript title="script.js" +// Change the primary color to green dynamically +document.documentElement.style.setProperty('--primary-color', '#4CAF50'); +``` + + +
+ +## Interactive CSS Variables Demo + +This example demonstrates how changing a single variable value can update multiple dependent styles at once, and how a local variable overrides a global one. + + + +In this demo, you can see how changing the value of `--theme-color` in the global scope affects the first box, while the second box uses its own local definition. \ No newline at end of file diff --git a/docs/css/advanced-features/inheritance.mdx b/docs/css/advanced-features/inheritance.mdx index e345ed2..68f0647 100644 --- a/docs/css/advanced-features/inheritance.mdx +++ b/docs/css/advanced-features/inheritance.mdx @@ -1 +1,131 @@ - \ No newline at end of file +--- +title: "CSS Inheritance and the Cascade" +description: "Understand how CSS properties are inherited from parent elements to children, how to control inheritance with specific property values, and its role within the CSS Cascade." +keywords: [CSS Inheritance, Cascade, inherit value, initial value, unset value, all property, text properties, box model properties] +tags: [CSS Inheritance, Cascade, inherit value, initial value, unset value, all property, text properties, box model properties] +sidebar_label: Inheritance +--- + +**Inheritance** is a fundamental mechanism in CSS where certain property values applied to a parent element are automatically passed down and applied to its descendant elements. + +This mechanism ensures that styles related to text and typography—like font, color, and line height—are applied consistently across an entire section of content without needing to explicitly target every single element. + + +
+ +## 1. Inherited vs. Non-Inherited Properties + +CSS properties are categorized into two groups regarding inheritance: + +### 1.1. Inherited Properties + +These properties relate primarily to text, color, and lists. When applied to a parent, they cascade down to all children. + +| Common Inherited Properties | +| :--- | +| `color` | +| `font-family`, `font-size`, `font-weight` | +| `line-height`, `text-align`, `text-indent` | +| `list-style` | +| `visibility`, `cursor` | + +### 1.2. Non-Inherited Properties + +These properties typically relate to the Box Model, layout, and visual display, and are intended to define the element's container or position. Applying them to a parent does **not** affect the children. + +| Common Non-Inherited Properties | +| :--- | +| `margin`, `padding` | +| `border` | +| `width`, `height` | +| `background-color`, `background-image` | +| `display`, `position` | +| `overflow` | + + +
+ +## 2. The Role of Inheritance in the Cascade + +Inheritance is the final stage in the browser's process of determining an element's style, known as the **Cascade**. + +The browser determines the final value of a property for an element using this priority order (simplified): + +1. **Origin:** Browser defaults, user styles, and author styles (your CSS). +2. **Specificity:** The winning rule from your CSS. +3. **Source Order:** The last rule wins if specificity ties. +4. **Inheritance:** If the property has *not* been set by any previous step, and the property is inheritable, the element receives the computed value from its direct parent. +5. **Default Value:** If none of the above apply, the browser uses the property's initial value (the browser's default for that specific property). + +## 3. Controlling Inheritance Explicitly + +You can manually control how inheritance works for any property using three special keyword values. + +### 3.1. `inherit` (Force Inheritance) + +The `inherit` keyword forces a property to take on the computed value of its immediate parent, even if the property is normally non-inherited. + +```css title="styles.css" +/* Example: Force a non-inherited border to be inherited */ +.child-box { + border: inherit; +} + +/* If the parent has `border: 2px solid black`, the child will get it. */ +.parent-box { + border: 2px solid black; +} +``` + +### 3.2. `initial` (Reset to Browser Default) + +The `initial` keyword sets a property to its default value as defined in the CSS specification (often the same as the user agent/browser style). + +```css title="styles.css" +/* Reset a child's color to the browser's default black, ignoring the parent's color */ +.special-link { + color: initial; +} +``` + +### 3.3. `unset` (Smart Reset) + +The `unset` keyword provides a smart way to reset a property based on whether it is naturally inherited or not: + + * **If the property is naturally inherited** (e.g., `color`), `unset` acts like `inherit`. + * **If the property is non-inherited** (e.g., `margin`), `unset` acts like `initial`. + +| Property | `unset` Result | +| :--- | :--- | +| `color` (Inherited) | `inherit` (Takes parent's color) | +| `background-color` (Non-inherited) | `initial` (Transparent) | + + +
+ +## 4. The `all` Property (Mass Reset) + +The `all` property is a shorthand that resets all CSS properties on an element to a single keyword value (`initial`, `inherit`, or `unset`). + +It is typically used to completely isolate a component from external styles. + +```css title="styles.css" +/* Resets ALL properties on the element to their initial (default) values. + This effectively makes the element look like it has no styles applied to it. */ +.isolated-component { + all: initial; +} +``` + +:::tip Using `all: unset` +`all: unset` is usually the most practical choice for mass resets. It allows naturally inherited properties (like `font-family`) to continue inheriting from the parent, while forcing non-inherited properties (like `margin`) back to their default `initial` values. This preserves readability while resetting layout. +::: + +## Interactive Inheritance Demo + +This demo illustrates which properties are inherited (color, font) and which are not (background, border). + + \ No newline at end of file diff --git a/docs/css/advanced-features/shadow-dom.mdx b/docs/css/advanced-features/shadow-dom.mdx index e345ed2..6c20b91 100644 --- a/docs/css/advanced-features/shadow-dom.mdx +++ b/docs/css/advanced-features/shadow-dom.mdx @@ -1 +1,136 @@ - \ No newline at end of file +--- +title: "Shadow DOM (CSS Encapsulation)" +description: "Explore the Shadow DOM, a key part of Web Components, and understand how it provides true CSS encapsulation to isolate styles and markup from the main document." +keywords: [Shadow DOM, Web Components, CSS encapsulation, shadow root, shadow host, '::part', '::slotted', style isolation] +tags: [Shadow DOM, Web Components, CSS encapsulation, shadow root, shadow host, '::part', '::slotted', style isolation] +sidebar_label: Shadow DOM +--- + +The **Shadow DOM** is one of the three core technologies (alongside Custom Elements and HTML Templates) that make up **Web Components**. Its primary purpose is to provide robust **encapsulation** for the internal structure and styling of a component. + +In standard CSS, styles are global, meaning a selector can accidentally or intentionally affect any element in the document. The Shadow DOM solves this by creating a hidden, separate DOM tree where CSS selectors only apply to its contents, and external styles cannot easily penetrate. + + +
+ +## 1. Key Terminology + +Understanding the Shadow DOM requires knowing its three main structural parts: + +| Term | Definition | +| :--- | :--- | +| **Shadow Host** | The regular DOM element to which the Shadow DOM is attached (e.g., ``). | +| **Shadow Tree** | The hidden DOM subtree that lives inside the Shadow Host. This contains the component's internal structure and styles. | +| **Shadow Boundary** | The border between the Shadow Tree and the regular DOM. This boundary enforces encapsulation. | +| **Shadow Root** | The root node of the Shadow Tree. This is created by calling `attachShadow()`. | + +### The Power of Isolation + +When CSS is placed inside the Shadow Tree: + +1. **Styles inside the Shadow Tree** apply only to elements within that tree. +2. **External styles** from the main document (the Light DOM) stop at the Shadow Boundary and do not affect the elements inside the Shadow Tree. + +## 2. Creating a Shadow Root (JavaScript) + +The Shadow DOM is typically created and managed via JavaScript using the `attachShadow()` method on a DOM element (the Shadow Host). + +### Mode: `open` vs. `closed` + +The `attachShadow()` method requires a configuration object with a `mode` property: + +| Mode | Accessibility | Description | +| :--- | :--- | :--- | +| **`open`** | **Accessible** | The Shadow Root can be accessed from outside the component using JavaScript (e.g., `element.shadowRoot`). This is generally preferred for debugging and flexibility. | +| **`closed`** | **Inaccessible** | The Shadow Root cannot be accessed directly from the outside. Styles and structure are fully hidden. | + +```javascript title="shadow-dom-setup.js" +// Get the host element (a custom element) +const host = document.querySelector('my-component'); + +// Create the Shadow Root, making it accessible (open) +const shadowRoot = host.attachShadow({ mode: 'open' }); + +// Add content and styles to the Shadow Tree +shadowRoot.innerHTML = ` + +

Hello from the Shadow DOM!

+`; +``` + + +
+ +## 3. Styling Across the Boundary (The Exceptions) + +While the Shadow DOM provides strong isolation, there are mechanisms to allow limited styling customization from the Light DOM. + +### 3.1. Targeting the Host (`:host()`) + +The `:host` pseudo-class allows you to style the Shadow Host element itself from *inside* the Shadow Tree. + +```css title="shadow-dom-styles.css" +/* Inside the Shadow DOM's