🔥Limited Offer: Get 50% OFFon AI & Full Stack Courses🔥
Back to CSS Notes
Topic #166

Variables in MQ


CSS Variables in Media Queries

Media Queries are about defining different style rules for different devices (screens, tablets, mobile phones, etc.). You can learn more Media Queries in our Media Queries Chapter.

Now we want to set one variable value for screens below 450px wide, and another variable value for screens above 450px wide.

Here, we first declare a new local variable named --fontsize for the .container class. We set its value to 20 pixels. Then, we create a @media rule that says "When the browser's width is 450px or wider, change the --fontsize variable value of the .container class to 40px.":

Example

  :root {
  --primary-bg-color: #1e90ff;
  --primary-color:
  #ffffff;
}

body {
  background-color:
  var(--primary-bg-color);
}

.container {
  --fontsize: 20px;

  color: var(--primary-bg-color);
  background-color:
  var(--primary-color);
  padding: 15px;
  font-size:
  var(--fontsize);
}

.container h2 {
  border-bottom: 2px
  solid var(--primary-bg-color);
}

@media screen and (min-width:
  450px) {
  .container {
    --fontsize: 40px;

  }
}

Here is another example where we also change the value of the --primary-bg-color variable in the @media rule:

Example

  :root {
  --primary-bg-color: #1e90ff;
  --primary-color:
  #ffffff;
}

body {
  background-color:
  var(--primary-bg-color);
}

.container {
  --fontsize: 20px;

  color: var(--primary-bg-color);
  background-color:
  var(--primary-color);
  padding: 15px;
  font-size:
  var(--fontsize);
}

.container h2 {
  border-bottom: 2px
  solid var(--primary-bg-color);
}

@media screen and (min-width: 450px) {
  .container {

  --fontsize: 40px;
  }
  :root {

  --primary-bg-color: lightblue;
  }
}

CSS var() Function

Function Description
var() Inserts the value of a CSS variable

Want to go beyond the notes?

Join CodingNow 2.0's CSS course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

Variables in MQ – FAQs

Quick answers about learning Variables in MQ in CSS.

This free note from CodingNow 2.0 explains Variables in MQ in CSS — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every CSS topic on CodingNow 2.0, including Variables in MQ, is 100% free with no signup required.
With focused practice, most students grasp Variables in MQ in 1–3 days from these notes; pairing it with CodingNow 2.0's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the CodingNow 2.0 Community (/community) — expert instructors answer within 24 hours.
WhatsApp
Call NowEnroll Now