How to make CSS DRY
I have seen these tricks in many places. But not as many as expected. All these tricks save you time and follow the DRY principle (sort of).
Use hsl()
These 3 colors are the same color with different lightness. The last percentage sets the lightness, but keeps the color and the darkness. Ideal for styling sites in a uniform way.
hsl(270, 60%, 50%); gives ---> Dark color
hsl(270, 60%, 70%); gives ---> Medium color
hsl(270, 60%, 90%); gives ---> Lite color
Use variables
Define all colour variables at the beginning of all CSS. Or in a separate CSS file.
:root {
--bg: hsl(270, 60%, 98%); //background
--dark: hsl(270, 60%, 50%);
--medium: hsl(270, 60%, 70%);
--lite: hsl(270, 60%, 90%);
--hover: hsl(253, 50%, 88%);
--select: hsl(270, 60%, 93%);
--black: hsl(0, 0%, 20%); //almost black
font-size: 110%;
}
Use these variables instead of #adfghh or rgb(100,100,100) by using var(--dark) etc. When you change the values of the variables every element that uses this variables automatically changes accordingly.
.line {
background-color: var(--dark);
width: 100%;
height: 1px;
margin-top: 8px;
margin-bottom: 15px;
}
Use rem
If you set the font-size in the root to 100% all font-sizes that are set to 1rem will be approximately 16 px. I use an accessibility standard of at least 18px which means a root size of appr 110%. You can resize all fonts by increasing or decreasing the value at root level.
:root {
font-size: 110%;
}
And you use this instead of em or px when setting sizes.
p {
font-size: 1rem;
color var(--black);
}