Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • CSS Tutorial
  • CSS Exercises
  • CSS Interview Questions
  • CSS Selectors
  • CSS Properties
  • CSS Functions
  • CSS Examples
  • CSS Cheat Sheet
  • CSS Templates
  • CSS Frameworks
  • Bootstrap
  • Tailwind
  • CSS Formatter
Open In App
Next Article:
CSS Website Layout
Next article icon

CSS Variables

Last Updated : 04 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

CSS variables (custom properties) are reusable values defined with two dashes (–) that make your CSS code efficient and easier to maintain.

  • Store values like colors, sizes, or fonts in one place for centralized updates.
  • Use var() to apply these variables anywhere in your CSS.
  • Improve code readability and consistency across your styles.

Syntax

var( --custom-name, value );

Parameters

  • –custom-name: (Required) The name of the custom property, starting with two dashes (–).
  • value: (Optional) A value used if the custom property is not defined or is invalid.
HTML
<!--Driver Code Starts{--> <html> <head> <!--Driver Code Ends }-->      <style>         :root {             --main-bg-color: lightblue;             --main-text-color: darkblue;         }         body {             background-color: var(--main-bg-color);             color: var(--main-text-color);         }     </style>  <!--Driver Code Starts{--> </head> <body>     <h1>Welcome to My Website</h1>     <p>This is a sample paragraph demonstrating CSS variables.</p> </body> </html> <!--Driver Code Ends }--> 

More Example of CSS Variable

1. Themed Button Using CSS Variables

HTML
<!--Driver Code Starts{--> <html> <head> <!--Driver Code Ends }-->      <style>         :root {             --button-bg: #4CAF50;             --button-text: white;             --button-padding: 10px 20px;         }         .btn {             background-color: var(--button-bg);             color: var(--button-text);             padding: var(--button-padding);             border: none;             cursor: pointer;         }         .btn:hover {             background-color: darkgreen;         }     </style>  <!--Driver Code Starts{--> </head> <body>     <button class="btn">Click Me</button> </body> </html>  <!--Driver Code Ends }--> 

In this example

  • :root defines –btn-bg for button background and –btn-text for button text color.
  • These variables are applied to style a button, making theme updates easy by changing values in :root.

2. Dynamic Spacing Using CSS Variables

HTML
<!--Driver Code Starts{--> <html> <head> <!--Driver Code Ends }-->      <style>         :root {             --spacing: 20px;         }         .box {             width: 100px;             height: 100px;             background-color: lightcoral;             margin: var(--spacing);         }     </style>  <!--Driver Code Starts{--> </head> <body>     <div class="box"></div>     <div class="box"></div> </body> </html>  <!--Driver Code Ends }--> 


In this example:

  • :root defines –spacing to set uniform spacing between boxes.
  • Changing the –spacing value in :root adjusts the margin for all .box elements.

Best Practices for CSS Variables

  • Define Variables in :root: Declare global variables within the :root selector to ensure they are accessible throughout your stylesheet.
  • Use Descriptive Naming: Choose clear and descriptive names for variables to enhance readability and maintainability.
  • Leverage the Cascade: Take advantage of CSS variables’ ability to inherit and be overridden within specific scopes, allowing for flexible theming and component styling.


Next Article
CSS Website Layout

M

MayankKhare
Improve
Article Tags :
  • CSS
  • Web Technologies
  • CSS-Basics

Similar Reads

  • CSS Opacity / Transparency
    The opacity in CSS is the property of an element that describes the transparency of the element. It is the opposite of transparency & represents the degree to which the content will be hidden behind an element. Try It: .custom-item { border: 1px solid gray; font-family: 'Gill Sans', 'Gill Sans M
    6 min read
  • CSS DropDowns
    Dropdown menus are essential for interactive websites, allowing users to access multiple links from a single menu. Using CSS, you can design stylish and functional dropdown menus that enhance the user experience. This article will cover various types of dropdowns and how to implement them using CSS.
    6 min read
  • CSS Links
    A link is a connection from one web page to another web page. CSS property can be used to style the links in various different ways.States of Link: Before discussing CSS properties, it is important to know the states of a link. Links can exist in different states and they can be styled using pseudo-
    5 min read
  • CSS Counters
    CSS counters allow you to number elements like lists or sections automatically. They are "variables" maintained by CSS, and their values can be incremented with CSS rules, tracking how many times they are used. To work with CSS counters, we use a set of properties: counter-reset: Creates or resets a
    3 min read
  • CSS Fonts
    CSS fonts control how text appears on a webpage. With CSS, you can specify various properties like font family, size, weight, style, and line height to create visually appealing and readable typography [GFGTABS] HTML <!--Driver Code Starts{--> <html> <head> <!--Driver Code Ends
    5 min read
  • CSS Colors
    CSS colors are used to set the color of different parts of a webpage, like text, background, and borders. This helps make the page look more attractive and easier to read. You can define colors using names, hex codes, RGB values, and more. You can try different formats of colors here- #content-ifram
    6 min read
  • CSS Multiple Columns
    CSS Multiple Columns is a property used to divide content into multiple columns, similar to a newspaper layout. It improves readability and organizes content efficiently across different screen sizes. Key Properties of CSS Multiple ColumnsBelow is a list of essential CSS properties for working with
    6 min read
  • CSS Attribute Selector
    CSS attribute Selector allows you to select elements based on the presence, value, or specific characteristics of their attributes. They are particularly useful for dynamic or structured content where attributes play a key role, such as in forms or data tables. Types of CSS Attribute Selectors1. [at
    5 min read
  • CSS Units
    CSS units define the size of elements, with absolute units (like px, cm) having fixed values and relative units (like em, rem, %, vh) depending on factors like the viewport or parent elements. There are two types of units: Absolute and Relative. Absolute unitsAbsolute units in CSS, such as px, cm, a
    10 min read
  • CSS Pseudo Elements
    A pseudo-element is a keyword added to a selector that lets you style specific parts of an element. For example, you can style the first line of a paragraph, add content before or after an element, or create complex effects with minimal code. Pseudo-elements are denoted by a double colon (::) (or :
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences