Oct 9, 2015

Introducing Media Query | CSS3

CSS3 has introduced new concept of Media query to assign different stylesheets depending on browser window size. It uses the @media rule to include a block of CSS properties only if a certain condition is true. You may use as many media queries as you would like in a CSS file.
Note that you may use and operator to require multiple queries to be true, but you have to use the comma (,) as or operator to separate groups of multiple queries. The not keyword can be used to alter the logic as well.
Example
If the browser window is smaller than 500px, the background color will change to blue:
@media only screen and (max-width: 500px) {
    body {
        background-color: blue;
    }
}

With media queries, rather than looking at what device it is, we will look at what capabilities the device has. More specifically, we will look at the following:
·         height and width of the device
·         height and width of the browser
·         screen resolution
·         orientation of the device (for mobile phones and tablets; portrait or landscape)

Max Width

The following CSS will apply if the viewing area is smaller than 600px.
@media screen and (max-width: 600px) {
  .class {
       background-color: blue;
  }
}
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: 600px)" href="small.css" />

Min Width

The following CSS will apply if the viewing area is greater than 900px.
@media screen and (min-width: 900px) {
  .class {
       background-color: blue;
  }
}

Multiple Media Queries

You can combine multiple media queries. The following code will apply if the viewing area is between 600px and 900px.
@media screen and (min-width: 600px) and (max-width: 900px) {
  .class {
      background-color: blue;
  }
}

Device Width

The following code will apply if the max-device-width is 480px (eg. iPhone display). Note: max-device-width means the actual resolution of the device and max-width means the viewing area resolution.
@media screen and (max-device-width: 480px) {
  .class {
      background-color: blue;
  }
}

Hope you liked the port. Connect with us on +Java Territory  to stay updated.


0 comments:

Post a Comment