CSS

CSS Overview Selectors Declarations Rule Sets Comments Reset/Normalize Origin Importance Order Specificity Inheritance Cascade Layers Inline Styles Internal Styles External Styles @import Absolute Units Relative Units Dynamic Viewport Angle Units Time Units Frequency Units: Resolution Units Keywords Color Formats Color Functions & Spaces Background Color Background Image Background Repeat Background Position Background Size Background Attachment Background Shorthand Multiple Backgrounds Linear Gradients Radial Gradients Conic Gradients Font Family Font Size Font Weight Font Style Line Height Text Align Text Decoration Text Transform Letter Spacing Word Spacing Text Shadow Text Wrap Variable Fonts Content Box Padding Box Border Box Margin Box Box Sizing Property Margin Padding Border Outline Box Shadow Block Display Inline Display Inline Block Display Static Position Relative Position Absolute Position Fixed Position Sticky Position Top Element Position Right Element Position Bottom Element Position Left Element Position Z Index Flexbox Box Layout Display Flex Flex Direction Flex Wrap Justify Content Align Items Align Content Gap, Row Gap & Column Gap Flex Grow Flex Shrink Flex Basis Flex Shorthand Order Property Align Self Practical Applications CSS Grid Layout Grid Display Grid Template Columns Grid Template Rows Grid Template Areas Justify Items Grid Auto Columns Justify Self Nested Grids Responsive Web Design Min Width Max Width Orientation Logical Operators Pointer Hover Prefers Color Scheme Fluid Images Flexible Typography Viewport Width Advanced CSS Features Defining variables Using variables Scope & Inheritance of CSS Variables Property Value Fallback Practical Applications :Hover :Active :Focus :Focus Visible :Visited :Link :First Child :Last Child :Nth Child :Nth of Type :Empty :Checked :Disabled :Enabled :Valid :Invalid :Required :Has :Not :Is :Where ::Before Pseudo Element ::After Pseudo Element ::First Letter ::First Line ::Selection ::Marker CSS 2D Transformations CSS 3D Transformations Transform Origin Transform Style Backface Visibility Transition Property Transition Duration Transition Timing Function Transition Delay Transition Shorthand Ease Timing Function Linear Timing Function Ease In Timing Function Ease Out Timing Function Ease In Out Timing Function Cubic Bezier Function Animations (@keyframes) Defining @keyframes Animation Name CSS Animation Duration Animation Timing Function CSS Animation Delay CSS Animation Iteration Count Animations Direction CSS Animation Fill Mode CSS Animation Play State CSS Filter Blur CSS Filter Brightness CSS Filter Contrast() CSS Drop Shadow CSS Grayscale CSS Hue Rotate CSS Invert CSS Opacity CSS Saturate CSS Sepia Mix Blend Mode Background Blend Mode Object Fit & Object Position Scroll Snap Type Scroll Snap Align Scroll Padding Scroll Margin Scroll Triggered Animations JS Variables

Scope & Inheritance of CSS Variables


Scope and Inheritance of CSS Variables

CSS variables, also known as custom properties, have a defined scope and follow the standard rules of inheritance. This allows for powerful and flexible styling, enabling developers to create more maintainable and dynamic stylesheets. Understanding how to control the scope and leverage inheritance is a fundamental skill for modern CSS development.


Example 1: Global Scope with :root

/* Defining a global variable within the :root pseudo-class */
:root {
  --main-bg-color: #f0f0f0;
}

body {
  background-color: var(--main-bg-color); /* Using the global variable */
}

div {
  border: 1px solid var(--main-bg-color); /* Inherited by descendant elements */
}

Explanation

Variables defined within the :root pseudo-class have a global scope, meaning they are accessible throughout the entire document. This is the standard practice for defining a site-wide color palette or font sizes that need to be used consistently.


Example 2: Local Scope

/* Defining a local variable within a specific class */
.container {
  --container-padding: 20px;
  padding: var(--container-padding);
}

.box {
  /* This would not work as --container-padding is not in this scope */
  /* margin: var(--container-padding); */
  margin: 10px;
}

Explanation

A variable declared inside a selector, like .container, has a local scope. It can only be accessed by the element with that class and its descendants, preventing unintended styles from leaking out to other elements.


Example 3: Overriding Global Variables

:root {
  --text-color: #333;
}

body {
  color: var(--text-color); /* Will be #333 */
}

.dark-theme {
  --text-color: #eee; /* Overriding the global variable for this class */
  color: var(--text-color); /* Will be #eee */
}

Explanation

Local variables will override global variables when applied to the same element. This is useful for creating themes or specific component styles that deviate from the global defaults.


Example 4: Inheritance in Action

.parent {
  --parent-font-size: 1.2rem;
  font-size: var(--parent-font-size);
}

.child {
  /* The --parent-font-size is inherited from .parent */
  /* The font-size of .child will be 1.2rem unless overridden */
}

Explanation

CSS variables are inherited by default. Any child element can use a variable defined in its parent, which simplifies styling nested components and ensures consistency within a specific section of your layout.


Example 5: Using Fallback Values

.element {
  /* The second value is a fallback if the first is not defined */
  background-color: var(--undefined-variable, #ff0000);
}

Explanation

The var() function can accept a second parameter which acts as a fallback value. If the custom property in the first parameter is not defined, the browser will use the fallback value instead, which helps prevent broken styles.


Example 6: Reassigning Variables

:root {
  --base-spacing: 10px;
}

.component {
  --base-spacing: 15px; /* Reassigning the variable for this component */
  padding: var(--base-spacing); /* Will be 15px */
}

Explanation

You can reassign the value of a custom property within a different scope. This powerful feature allows for creating variations of a component without writing entirely new CSS rules, promoting reusability.


Example 7: Combining Variables

:root {
  --base-font-size: 16px;
  --font-scale: 1.5;
}

h1 {
  /* Variables cannot be directly combined with units like this */
  /* font-size: var(--base-font-size) * var(--font-scale); */

  /* Use calc() to combine them */
  font-size: calc(var(--base-font-size) * var(--font-scale));
}

Explanation

While you cannot directly concatenate or perform mathematical operations with variables in a property value, you can use the calc() function. This enables dynamic calculations based on your defined custom properties for creating responsive and scalable typography or layouts.