Skip to content
Siddharth Blog
Go back

CSS Media Queries Guide

Media queries are a powerful tool in web development that allow you to apply different styles to your webpage based on screen size, resolution, or device type.

This guide will help you understand the basics with simple examples.


1. What are Media Queries?

Media queries are CSS rules that apply styles depending on certain conditions.

@media screen and (max-width: 600px) {
  /* Styles for small screens */
}

2. Basic Media Query Examples

Adjusting Font Size

p {
  font-size: 16px;
}

@media screen and (max-width: 600px) {
  p {
    font-size: 14px;
  }
}

Hiding Elements

.sidebar {
  display: block;
}

@media screen and (max-width: 800px) {
  .sidebar {
    display: none;
  }
}

3. Min and Max Width

Minimum width

@media screen and (min-width: 600px) {
}

Maximum width

@media screen and (max-width: 600px) {
}

Range

@media screen and (min-width: 600px) and (max-width: 900px) {
}

4. Combining Media Queries

body {
  background-color: #f0f0f0;
}

@media screen and (min-width: 600px) and (max-width: 1200px) {
  body {
    background-color: #dcdcdc;
  }
}

5. Responsive Images

img {
  max-width: 100%;
  height: auto;
}

@media screen and (max-width: 600px) {
  img {
    width: 100%;
  }
}

6. Automatic Dark Mode

@media (prefers-color-scheme: dark) {
  body {
    background-color: black;
    color: white;
  }
}

Final Thoughts

Media queries are essential for building responsive websites. Once you understand them, you can make your site look good on mobile, tablet, and desktop.

Start simple, test often, and gradually build more complex layouts.


Share this post on:

Previous Post
How to add live code previews to your website