Custom Selectors, also known as CSS variables, offer flexibility and maintainability in styling web pages. They allow us to define our own selectors and reuse them throughout our stylesheets. This makes our CSS more modular and easier to manage.
The syntax for defining a custom selector is straightforward
:root {
--custom-selector: value;
}
Here, --custom-selector
is the name of our custom selector, and value
is the value associated with it.
:root {
--main-color: #007bff; /* Defining a custom selector for main color */
}
Once defined, we can use custom selectors anywhere within our CSS code by referencing them using the var()
function
.selector {
color: var(--main-color); /* Using the custom selector */
}
CSS Custom Selectors Example
This text should be colored with the main color.
In this example, we define a custom selector --main-color
with the value #007bff
. Then, we use this custom selector within the .selector
class to set the text color.
Output: The text inside the .selector
class will be colored with the main color #007bff
.
Custom Selectors offer more than just simple variable substitution. Let’s explore some advanced techniques
We can use custom selectors within media queries to make our styles adapt to different screen sizes
@media (max-width: 768px) {
.selector {
font-size: var(--small-font-size);
}
}
Custom selectors can be nested within other selectors, allowing for more complex styling
.parent {
--text-color: red;
}
.child {
color: var(--text-color);
}
JavaScript can be used to dynamically manipulate custom selectors, providing even greater flexibility
document.documentElement.style.setProperty('--main-color', '#ff0000');
Let’s dive into some practical examples to solidify our understanding
Custom selectors are excellent for theming. Let’s create a light and dark theme
:root {
--main-background: #fff;
--main-text-color: #333;
}
.dark-theme {
--main-background: #333;
--main-text-color: #fff;
}
body {
background-color: var(--main-background);
color: var(--main-text-color);
}
Custom selectors can simplify responsive typography
:root {
--base-font-size: 16px;
}
@media (min-width: 768px) {
:root {
--base-font-size: 18px;
}
}
body {
font-size: var(--base-font-size);
}
CSS Custom Selectors Practical Examples
Theming Example
This text is styled differently for a dark theme.
Responsive Typography Example
This text adjusts its font size based on the viewport width.
Output: The HTML document will display examples of theming and responsive typography using custom selectors.
In this chapter, we've covered everything from the basics to advanced techniques of CSS Custom Selectors. By understanding and utilizing custom selectors effectively, you can write cleaner, more maintainable, and flexible CSS code for their web projects. Happy coding! ❤️