Connect with us

CSS

CSS: How to Change Styles Based on Screen Size (Responsive Design with Media Queries)

Spread the love

Modern websites need to look great on all devices—from large desktop monitors to small mobile screens. This is where responsive design comes in. By using CSS media queries, you can change styles depending on the screen size, resolution, orientation, and more.

In this blog post, you’ll learn:

  • ✅ How to change CSS styles based on screen width
  • ✅ How media queries work
  • ✅ Real-world responsive examples
  • 📱 Tips for building mobile-friendly layouts

✅ 1. What Are CSS Media Queries?

Media queries are a feature in CSS that allow you to apply styles only when certain conditions (like screen width) are met.

✅ Basic Syntax:

@media (max-width: 768px) {
  /* Styles for screens smaller than 768px */
}

This means: If the screen is 768 pixels wide or less, apply the styles inside this block.


✅ 2. Example: Change Background Color on Small Screens

body {
  background-color: white;
}

@media (max-width: 600px) {
  body {
    background-color: lightgray;
  }
}

✅ On large screens: background stays white
✅ On screens ≤600px: background changes to light gray


✅ 3. Responsive Text and Font Sizes

You can adjust font sizes based on screen size for better readability.

h1 {
  font-size: 36px;
}

@media (max-width: 768px) {
  h1 {
    font-size: 28px;
  }
}

@media (max-width: 480px) {
  h1 {
    font-size: 22px;
  }
}

✅ This ensures your headings scale well across devices.


✅ 4. Responsive Layout with Flex or Grid

For layout changes:

.container {
  display: flex;
  flex-direction: row;
}

@media (max-width: 768px) {
  .container {
    flex-direction: column;
  }
}

✅ This changes a horizontal layout to vertical on smaller screens.


✅ 5. Common Breakpoints (Best Practice)

Here are some standard breakpoints used in responsive design:

Device TypeBreakpoint (max-width)
Large desktops1200px
Laptops992px
Tablets768px
Phones600px or 480px

Example usage:

@media (max-width: 992px) {
  /* styles for tablets and below */
}

🧠 Tips for Responsive CSS

  • ✅ Start with a mobile-first approach (min-width)
  • ✅ Use relative units (em, rem, %) for scalable design
  • ✅ Test on real devices and emulators
  • ✅ Keep layout simple and fluid where possible

🏁 Final Thoughts

Changing CSS based on screen size using media queries is the foundation of responsive web design. With just a few lines of CSS, you can make your website look great on phones, tablets, laptops, and desktops—ensuring a consistent and user-friendly experience across all devices.


Spread the love
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *