CSS css variables
Created By: chatGPT
CSS variables, also known as custom properties, provide a way to store values that can be reused throughout your CSS. They follow a specific syntax and can help in maintaining and managing styles more effectively. You declare a CSS variable using the
--
prefix and can access it using the var()
function.:root {
--main-bg-color: lightblue;
--main-text-color: darkblue;
}
body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
}
You can define your CSS variables within any selector, but it's common to declare them in the
:root
pseudo-class, which represents the root element of the document. This makes your variables accessible throughout your entire stylesheet.:root {
--font-size: 16px;
--line-height: 1.5;
}
p {
font-size: var(--font-size);
line-height: var(--line-height);
}
CSS variables can also be overridden. If you define the same variable in a different scope, it takes preference in that scope. This feature can be particularly useful for theming or adjusting styles in specific contexts.
.container {
--main-bg-color: lightgreen;
}
.container {
background-color: var(--main-bg-color);
}
.other {
background-color: var(--main-bg-color);
}
Another advantage of CSS variables is that they can be updated dynamically using JavaScript, allowing you to change styles on-the-fly without needing to manipulate individual styles directly.
const root = document.documentElement;
function changeTheme() {
root.style.setProperty('--main-bg-color', 'black');
root.style.setProperty('--main-text-color', 'white');
}
CSS variables provide both flexibility and consistency. They allow you to maintain uniform styles across different parts of a web application while making it easier to update them globally as needed. As a result, using CSS variables can lead to more maintainable and scalable CSS code.
button {
background-color: var(--main-bg-color);
color: var(--main-text-color);
padding: 10px;
border: none;
border-radius: 5px;
cursor: pointer;
}