Media Queries- Notes By ShariqSP

Understanding Media Queries in CSS

Media queries are an essential tool in responsive web design. They allow developers to apply different styles based on the properties of the device or viewport. By using media queries, websites can adapt their layout and design to provide an optimal user experience across various screen sizes, orientations, and resolutions.

How Media Queries Work

A media query consists of a CSS rule that is applied only if a specified condition is met. Common conditions include the viewport width, height, resolution, and orientation. For example, you can apply different styles for mobile devices, tablets, and desktops based on the screen width.

Media Query Syntax

        @media (condition) {
            /* CSS rules here */
        }
                

Example of targeting screens narrower than 768px:

        @media (max-width: 768px) {
            body {
                background-color: lightblue;
            }
        }
                

Real-World Example: Responsive Navigation Bar

Consider a website with a navigation bar. On larger screens, the navigation bar is displayed horizontally, but on smaller screens, it changes to a vertical layout for better usability. Here's the implementation:

HTML

        
                

CSS

        /* Default (large screens) */
        .navbar {
            display: flex;
            justify-content: space-around;
            background-color: #333;
            color: white;
            padding: 10px 0;
        }

        .navbar li {
            list-style: none;
            padding: 10px 20px;
        }

        /* Media Query for small screens */
        @media (max-width: 768px) {
            .navbar {
                display: block;
                text-align: center;
                background-color: #444;
            }

            .navbar li {
                display: block;
                padding: 15px 0;
            }
        }
                

Output

On a large screen, the navigation bar is horizontal:

Horizontal Navbar

On a small screen, it changes to a vertical layout:

Vertical Navbar

Why Use Media Queries?

  • Improve usability on different devices (mobile, tablet, desktop).
  • Create responsive designs without duplicating code.
  • Optimize performance by hiding or resizing elements.

Best Practices

  • Adopt a mobile-first approach: Start with the styles for smaller screens and progressively enhance for larger ones.
  • Test your design on multiple devices to ensure compatibility.
  • Use breakpoints wisely. Common breakpoints include 480px, 768px, 1024px, and 1200px.