Use class
when you wish to apply a group of styles to many HTML elements, and unique id
selectors for styling only a single element. You can also utilize CSS Variables for reusable values, there are a few ways to go about doing so. In general, you declare a custom variable by using a custom property name that begins with a double hyphen --
, and a property value that can be any valid CSS value. Using var()
allows us to insert the value of custom property (variable). If the custom property should be more than word, separate each word with a hyphen (kebab case).
- Target the
:root
element and define variables:
:root {
--my-cool-prop: #f06;
}
.my-selector {
color: var(--my-cool-prop);
}
- Create the custom property inside the selector:
.some-selector {
--some-prop: 16px;
--some-other-prop: blue;
font-size: var(--some-prop);
background-color: var(--some-other-prop);
}
So lets say you have four different HTML pages, you can use a single stylesheet (or multiple if you have a bunch of CSS and opt for a more modular approach) to define some custom variables and use them in the selectors you wish to style. Remember if you define a variable in style.css
and try using it in another CSS file other-style.css
it won't be available. When using var()
you can also define multiple fallback values if the given variable isn't defined.
:root {
--my-cool-prop: #f06;
}
.my-selector {
color: var(--my-cool-prop, #000); /* black if --my-cool-prop is undefined */
}
.some-selector {
--some-prop: #fff;
--some-other-prop: blue;
color: var(--some-prop, red); /* red if --some-prop is undefined */
background-color: var(--some-other-prop, green); /* green if --some-other-prop is undefined */
}
<body>
<h1 class="my-selector">Some title</h1>
<div class="some-selector">
<h2>Some other title</h2>
</div>
</body>