Signup/Sign In

Media Query breakpoints in CSS

There are various types of devices used in today's world. The width and height of one device vary from the other. From small screen mobiles, medium screen tablets, and large screen computers the webpages have to adjust themselves according to the height and width of the devices.

The self-adjustment of the webpage according to the device's screen size is called a responsive webpage. This can be done using the Media Query rule.

In this tutorial, we are going to learn how to create media Query breakpoints with CSS.

Media Query breakpoints

The breakpoint is a pixel value of the viewport which can be used to customize the HTML element for that viewport. We can define the viewport using max-width or min-width property.

The CSS property for any particular breakpoint is defined using the media query rule. An alternate section of a CSS property is added with @media rule with the type screen to add CSS for that particular breakpoint (screen size).

We can define any number of Media Query breakpoints for a webpage. But that will increase complications of code. So use some standard breakpoints.

Example: Customizing HTML elements at the different breakpoint

Here, we will take a small example where we will change the text color at the specified breakpoints.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
    @media only screen and (max-width: 400px) {
	  .text {
	  color: red;}
	  }
	@media only screen and (min-width: 600px) {
	  .text {
	  color: blue;}
	  }
	@media only screen and (min-width: 800px) {
	  .text {
	  color: pink;}
	  }
	@media only screen and (min-width: 1000px) {
	 .text {
	  color: green;}
	  }
	@media only screen and (min-width: 1100px) {
	 .text {
	  color: yellow;}
	  }
	@media only screen and (min-width: 1200px) {
	  .text {
	  color: violet;}
	  }	 
</style>
</head>
<body>
   <div class="text">
	   <h2> Resize your screen to see effects</h2>
	   <p> changing text color at defined breakpoints </p>
	</div>
</body>
</html>

Output

Here is the output for the viewport with a minimum width of 600px.

media query breakpoints

Example: Responsive grid images using media query breakpoints

In the example, we have 4 breakpoints. The number of images increases per row as the width of the screen increases.

Conclusion

In this tutorial, we have learned to use media query breakpoints to the elements. We can define the breakpoints for creating responsive elements. Though we can define any number of breakpoints in our code but it will make the code lengthy so take some standard breakpoints.



About the author: