Skip to main content

Command Palette

Search for a command to run...

Media Query

An important part of responsive web design

Published
2 min readView as Markdown
Media Query

Introduction

Today, people use different kinds of devices to view web pages. These devices have different kinds of screen sizes. Media queries help to apply styles using CSS that suits the device screen type or browser viewport width.

Syntax

Media query consists of an optional media type and any number of media feature expressions that can be used with various combinations using logical operators.

  • @media is used that wraps elements with conditions for when and where to apply a set of styles when a browser matches those conditions.

Media query for max-width

A @media can be set with a maximum width. Up to that width, a specific kind of style can be set which will come into effect in the document.

@media all and (max-width:768px) {
    .element {
        color: red;
        display: flex;
        flex-direction: column;
    }
}

Media query with min and max width

@media all and (min-width: 480px) and (max-width: 768px) {
.element {
    background-color: #F5F5DC;
    font-size: 14px;
    } 
}

Media query with min-width and min-height

@media all and (min-width: 1280px) and (min-height: 600px) {
.element {
    background-color: #FFA500;
    font-size: 20px;
    } 
}

Orientation in CSS media queries

Responsiveness can never be achieved if the web application cannot understand the orientation and respond accordingly. As per the requirement, landscape or portrait can be used in @media.

@media (orientation: landscape) {
    .element {
        width: 80%;
        height: 30vh;
      }
}

Thank you for reading.