Signup/Sign In

CSS Custom Properties and Media Queries

The CSS custom property is dynamic in nature which means it allows us to define and redefine the value of the custom property even inside the media query. We can perform all the tasks on custom properties inside the @media which we can perform inside the HTML element.

Syntax of CSS media query

@media screen and (max-width: 900px) {
element {
/* CSS property*/ 
}
}

Example: Specifying CSS media queries

In this example, we have first declared a custom property --font-size inside the :root element and use it in the .container class. Then, we have created a @media rule which specifies when the browser's width is 450px and more, then the --font-size value of the .container class changes to 50px.

<!DOCTYPE html>
<html>
<head>
	<title>CSS Custom Property and Media Query</title>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<style>
		/* Variable declarations */ 
		:root {
		  --blue:#97f7ec;
		  --white: #ffffff; 
		}

		.container {
		  --font-size: 25px;
		}

		/* Styles */ 
		body {
		  background-color: var(--blue);
		}

		h2 {
		  border-bottom: 2px solid var(--blue);
		}

		.container {
		  color: var(--blue);
		  background-color: var(--white);
		  padding: 15px;
		  font-size: var(--fontsize);
		}

		@media screen and (min-width: 450px) {
		  .container {
		    --font-size: 50px;
		  }
		}
	</style>
</head>
<body>
<div class="container">
  <p>When the browser's width is less than 450px, the font-size of this div is 25px. When it is 450px or wider, set the --font-size variable value to 50px. Resize the browser window to see the effect.</p>
</div>
</body>
</html>

Output:

Live Example

In the given example, we have created the two custom properties --blue and --white within the : root pseudo-class and one inside the .container class (--fontsize). Then we specified the media query so, when the browser width is 450px and more than that then the font-size changes from 15px to 35px and the background-color turns from light green to light blue.

Conclusion

In this lesson, we have learned how to implement media queries in CSS. We have also learned how to change the value of the properties at specific screen sizes using media queries.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight