CSS custom properties
Created By: chatGPT
CSS custom properties, also known as CSS variables, allow you to store values that can be reused throughout your CSS. This not only makes your styles easier to maintain but also enhances flexibility. Custom properties are defined using a specific syntax: they begin with two dashes (
--
).:root {
--main-bg-color: #ffcc00;
--main-text-color: #333;
}
You can access these custom properties using the
var()
function. This allows you to apply the value anywhere in your stylesheet, promoting reusability.body {
background-color: var(--main-bg-color);
color: var(--main-text-color);
}
Custom properties can be particularly useful when you want to maintain a consistent design across your application. If you need to change a color, you only have to update it in one place.
.button {
background-color: var(--main-bg-color);
color: var(--main-text-color);
padding: 10px 20px;
border: none;
border-radius: 5px;
}
.button:hover {
background-color: darken(var(--main-bg-color), 10%);
}
Custom properties are responsive as well. They can be redefined at different screen sizes, allowing you to adjust styles for mobile, tablet, and desktop views seamlessly.
@media (max-width: 600px) {
:root {
--main-bg-color: #333;
--main-text-color: #fff;
}
}
Keep in mind that custom properties are scoped to the element they are declared on. If you define a property within a specific class, it will not be available outside of that class unless declared at a higher level like
:root
..card {
--border-radius: 10px;
border-radius: var(--border-radius);
}
.card-large {
--border-radius: 20px;
}
By using CSS custom properties effectively, you can significantly reduce duplication and enhance the maintainability of your stylesheets, leading to better, more manageable code.
h1 {
color: var(--main-text-color);
}
p {
color: var(--main-text-color);
margin-top: 1rem;
}