CSS Variables are very powerful, saves time, and make us easier to make changes while building websites without depending on the preprocessor.
There are two ways to use it while working with a responsive website. The first is to define sizes, colors, typography, etc. differently for mobile and desktop, and second, create the same variables under a media query and change the values.
We are going with the mobile-first design. Let’s start with the basics.
:root { --color: #000; }
I created a variable –color: #000; under root(parent), now we will use it by writing the CSS for an element.
h2 { color: var(--color); }
now, how we can use CSS variables in the responsive designs. Let’s look at the methods we can use.
Method 1. Different Variables for Mobile and Desktop
We are going to create different sizes for our h2 heading which we will use differently for each device.
:root { --mobileH2: 15px; --desktopH2: 20px; }
and now the CSS for heading for each device.
h2 { font-size: var(--mobileH2); } @media screen and (min-width: 768px) { h2 { font-size: var(--desktopH2); } }
Here we have created two variables, each for mobile and desktop, and used them respectively. Here we are using the different variables depending on the media screen.
Method 2. Different Media Query for Variables
In this method, we will create two variables one for mobile and one for desktop, and will use a single CSS for our heading.
:root { --h2size: 15px; } @media screen and (min-width: 768px) { :root { --h2size: 20px; } }
and our heading CSS.
h2 { font-size: var(--h2size); }
Here the:root automatically selects the appropriate variable based on the media query. Here, we are overwriting the root variables.
It is recommended to learn it and start using it in your next website design. Coderve Tutorials will also include variables CSS which will be easier to work with.
to learn more about CSS Variables, visit MDN Web Docs. We will also cover CSS value definition syntax in the future.