Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

CSS3 Media Queries

CSS3 Media Queries


CSS2 Media Types

@media Rules were introduced in CSS2, allowing different style rules to be customized for different media types.

For example: you can set different style rules for different media types (including screens, portable devices, televisions, etc.).

However, these media types are not well supported on many devices.


CSS3 Media Queries

CSS3 media queries inherit all the ideas of CSS2 media types: instead of finding the device type, CSS3 adapts the display according to the settings.

Media queries can be used to detect many things, such as:

Currently many devices such as iPhones, Android phones, and tablets use media queries.


Browser support

The numbers in the table indicate the version number of the first browser that supports this property.

property
@media 21.0 9.0 3.5 4.0 9.0

Media Query Syntax

A media query consists of various media and can contain one or more expressions, which return true or false depending on whether the condition is met.

@media

not

|

only

mediatype

and

(

expressions

)

{

CSS

code...;

}

If the specified media type matches the device type, the query returns true and the document is displayed with the specified style on the matching device.

Unless you use the not or only operators, all styles will apply to all devices.

You can also use different style files for different media:

<

link

rel

="

stylesheet

"

media

="

mediatype

and

|

not

|

only

(

expressions

)"

href

="

print

.css

">

Using media queries, you can use corresponding styles to replace the original styles on specified devices.

In the following example, the background color is changed on devices whose screen viewport size is less than 480 pixels:

Example

@media

screen

and

(max-width: 480

px

)

{

body

{

background-color:

lightgreen

;

}

}

Try it »

The following example floats the menu to the left side of the page when the screen viewport size is greater than 480 pixels:

Example

@media

screen

and

(min-width: 480

px

)

{

#leftsidebar

{

width:

200

px

;

float:

left

;

}

#main

{

margin-left:

216

px

;

}

}

Try it »

The following example hides the div element when the screen viewport size is less than 600 pixels:

Example

@media

screen

and

(max-width: 600

px

)

{

div

.example

{

display:

none

;

}

}

Try it »


CSS3 @media Reference

For more media query content, refer to @media rules.