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

Using variables


Using variables (var(--variable-name))

CSS custom properties, more commonly known as CSS variables, are entities defined by CSS authors which contain specific values to be reused throughout a document. They are set using custom property notation (e.g., --main-color: black;) and are accessed using the var() function (e.g., color: var(--main-color);). This allows for more maintainable and scalable CSS by centralizing values.


Example 1: Basic Variable Declaration and Usage

/* styles.css */
:root {
  --primary-color: #3498db; /* Declaring a global variable for the primary color */
}

.button {
  background-color: var(--primary-color); /* Using the variable for the button's background */
  color: white;
  padding: 10px 20px;
}

Explanation

The --primary-color variable is declared within the :root pseudo-class, making it available globally. The .button class then uses var(--primary-color) to set its background-color, demonstrating a simple and direct application of a CSS variable.


Example 2: Fallback Values

/* styles.css */
.alert {
  /* Using a fallback value in case --alert-color is not defined */
  background-color: var(--alert-color, #f1c40f);
  padding: 15px;
  border: 1px solid #ddd;
}

Explanation

This example shows how to provide a fallback value in the var() function. If --alert-color is not defined anywhere in the CSS, the browser will use the second parameter, #f1c40f, as the background-color for the .alert class.


Example 3: Local Scope

/* styles.css */
.container {
  --container-padding: 20px; /* Variable with local scope to .container */
  padding: var(--container-padding);
  background-color: #ecf0f1;
}

.container .box {
    /* This will work as .box is a descendant of .container */
    margin-bottom: var(--container-padding);
}

Explanation

The --container-padding variable is scoped to the .container class and its descendants. Any element outside of .container cannot access this variable, which is useful for component-specific styling.


Example 4: Theming a Website

/* styles.css */
.theme-dark {
  --background-color: #2c3e50;
  --text-color: #ecf0f1;
}

.theme-light {
  --background-color: #ffffff;
  --text-color: #2c3e50;
}

body {
  background-color: var(--background-color);
  color: var(--text-color);
}

Explanation

CSS variables are excellent for theming. By changing the class on the body element (e.g., from theme-light to theme-dark), all the elements using --background-color and --text-color will update their styles accordingly.


Example 5: Building a Consistent Spacing System

/* styles.css */
:root {
  --spacing-unit: 8px; /* Base spacing unit */
}

.header {
  padding: calc(var(--spacing-unit) * 2); /* 16px */
}

.article {
  margin-bottom: calc(var(--spacing-unit) * 3); /* 24px */
}

Explanation

A base --spacing-unit is established to create a consistent spacing scale. The calc() function is used with the variable to define different sizes for padding and margin across various elements, ensuring a harmonious layout.


Example 6: Using Variables in Media Queries

/* styles.css */
:root {
  --font-size: 16px; /* Default font size */
}

@media (min-width: 768px) {
  :root {
    --font-size: 18px; /* Larger font size on larger screens */
  }
}

body {
  font-size: var(--font-size);
}

Explanation

This demonstrates how to change the value of a CSS variable within a media query. The body's font-size will be 16px on smaller screens and will automatically update to 18px on screens that are 768px or wider.


Example 7: Dynamic Values with JavaScript

/* styles.css */
:root {
  --highlight-color: #3498db;
}

.interactive-element {
  transition: background-color 0.3s ease;
  background-color: var(--highlight-color);
}

JavaScript

/* script.js */
const element = document.querySelector('.interactive-element');

element.addEventListener('mouseover', () => {
  // Changing the CSS variable's value with JavaScript
  document.documentElement.style.setProperty('--highlight-color', '#e74c3c');
});

Explanation

CSS variables can be manipulated with JavaScript to create dynamic and interactive effects. In this case, when a user hovers over the .interactive-element, a JavaScript event listener updates the --highlight-color variable, which in turn changes the element's background-color.