tutorialstonight logo
A Platform To Learn To Code

CSS MEDIA QUERIES



Media query is a technique in CSS3 which lets users define different styles for different devices as well as for different screen sizes.

Media query is useful when you want to design webpage auto adjust according devices like Desktop, laptop, pads, tablet, mobile etc.

Media query can do following tasks:

  • Conditionally apply CSS properties to the elements of the webpage.
  • It can load different resources only for targeted device or targeted screen size.
  • It will load an external CSS file which is attached for a media query even when the query is false in <link> but will not apply its property to the page until condition is true.



media query syntax

A media query is composed of media type, logical operation and condition. A media query starts with @media keyword followed by media type and conditions separated by logical operation.

Example


Syntax explanation

  • not : This reverses the meaning of the media query.
  • only : This only keyword is used to apply style only when all the media query matches, also it prevents older browsers from applying style correctly.
  • media-type : Media-type could be anything like all, screen, printer or speech.
  • and : This connects media-type and media feature.
  • media feature : This describes the status of media type on the parameters like width, max-width, min-width, height, min-height, max-height, resolution, aspect-ratio etc.


media query min-width

The min-width in media query is used to set CSS properties which works only when the minimum width of the media type (screen) is greater than specified.

Example

Run the code

Note : media queries must be last to define in style because defined styles are taken into consideration from top to down, if any media query is defined for any selector before defining normal CSS for that selector then the media query is ignored.

media query max-width

The max-width in media query is used to set CSS properties which works only when the maximum width of the media type (screen) is smaller than specified.

Example

Run the code

media query for use for containers

Using media-query you can handle containers how they align in different screen sizes.

Example

Run the code

Media Query display none

Using media-query you can hide/show div element or any other element.

Example

Run the code