Wednesday, October 13, 2010

How to detect screen size in CSS?

CSS3 Media Queries

Max Width
The following CSS will apply if the viewing area is smaller than 500px.
<style type="text/css">
@media screen and (max-width: 500px) {
.class { background: #ccc; }
}
</style>

If you want to link to a separate stylesheet, put the following line of code in between the <head> tag.
<link rel="stylesheet" media="screen and (max-width: 500px)" href="small.css" />

Min Width
The following CSS will apply if the viewing area is greater than 800px.
<style type="text/css">
@media screen and (min-width: 800px) {
.class { background: #666; }
}
</style>

Multiple Media Queries
You can combine multiple media queries. The following code will apply if the viewing area is between 500px and 800px.
<style type="text/css">
@media screen and (min-width: 500px) and (max-width: 800px) {
.class { background: #333; }
}
</style>

* Media query is not supported in Internet Explorer 8 or older. You can use Javascript to hack around.

Example:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Media Query Demos</title>
<style type="text/css">
.box { margin:10px; padding:10px; border:1px solid #666;}
/* max-width */
@media screen and (max-width: 500px) {
.max { background: #18d; }
}
/* min-width */
@media screen and (min-width: 800px) {
.min { background: #18d; }
}
/* min-width & max-width */
@media screen and (min-width: 500px) and (max-width: 800px) {
.between { background: #18d; }
}
</style>
</head>
<body>
<div class="box max">This box will turn to blue if the viewing area is less than 500px</div>
<div class="box min">This box will turn to blue if the viewing area is greater than 800px</div>
<div class="box between">This box will turn to blue if the viewing area is between 500px and 800px</div>
</body>
</html>

No comments:

Post a Comment