DEV Community

Cover image for Responsive Design with CSS Media Queries
Muhammad Azhar Iqbal
Muhammad Azhar Iqbal

Posted on

Responsive Design with CSS Media Queries

Hello, Developers! 🌟

Today, we're going to explore the magical world of Responsive Web Design. We all know how essential it is for websites to look good on all devices. Thanks to CSS Media Queries, making a site responsive has never been easier.

What are Media Queries?

Media Queries allow us to apply different styles for different media types and screen sizes. You can change the layout, fonts, colors, and other design elements depending on the device's viewport size.

Basic Syntax

The most straightforward media query syntax looks like this:

@media screen and (min-width: 768px) {
  /* Your CSS here */
}
Enter fullscreen mode Exit fullscreen mode

Let's Get Practical!

Imagine you have a simple HTML layout:

<!DOCTYPE html>
<html>
<head>
  <title>Responsive Design</title>
  <link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
  <div class="container">
    <h1>Welcome to My Website</h1>
    <p>This is a sample paragraph.</p>
  </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

And your CSS:

.container {
  width: 100%;
  margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

Adding Responsiveness

We'll use media queries to change the .container width when the viewport is at least 768px:

@media screen and (min-width: 768px) {
  .container {
    width: 70%;
  }
}
Enter fullscreen mode Exit fullscreen mode

Now your container will take up 70% of the screen only when the screen width is 768px or larger. Simple, isn't it?

Top comments (0)