Skip to main content

Media Queries (Live Playground)

In this tutorial, we will discuss how to use media queries to create responsive web designs that adapt to different devices and screen sizes. Media queries are a CSS technique that allows you to apply different styles depending on the characteristics of the user's device, such as screen size, resolution, and orientation.

What are media queries?

Media queries are a feature of CSS3 that allow you to apply different CSS styles depending on the user's device's characteristics, such as screen size, resolution, and orientation. This enables you to create responsive designs that look good on a wide range of devices, from small mobile phones to large desktop monitors.

How to use media queries

To use media queries, you need to define them in your CSS file or within a <style> tag in your HTML file. A media query consists of a media type (such as screen) and one or more conditions (such as min-width or max-width) that must be met for the associated CSS rules to be applied.

Here's an example of a simple media query that applies different background colors to the body element based on the screen's width:

CSS
/* Default styles */
body {
background-color: lightblue;
}

/* Styles for screens with a minimum width of 300px */
@media screen and (min-width: 300px) {
body {
background-color: lightgreen;
}
}

/* Styles for screens with a minimum width of 600px */
@media screen and (min-width: 600px) {
body {
background-color: lightcoral;
}
}

In this example, we have defined three sets of styles:

  1. Default styles that apply to all devices.
  2. Styles for screens with a minimum width of 300 pixels, such as tablets in landscape mode.
  3. Styles for screens with a minimum width of 600 pixels, such as desktop monitors.

To use these media queries in your HTML, simply include the CSS in a <style> tag or link to an external CSS file:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Media Queries Example</title>
<style>
/* Insert the media queries CSS here */
</style>
</head>
<body>
<h1>Welcome to our responsive web page!</h1>
<p>The background color of this page changes depending on your screen's width.</p>
</body>
</html>
Live Playground, Try it Yourself

Conclusion

In this tutorial, we have discussed how to use media queries to create responsive web designs that adapt to different devices and screen sizes. By incorporating media queries into your CSS, you can ensure that your website looks great and functions well on a variety of devices, providing a better user experience.