CSS3 Media Queries

Datetime:2016-08-23 03:05:53          Topic: CSS3           Share

Currently the best method for designing responsive websites are with media queries. They allow the css of a website to change depending on the screen size.

Set up

Create an index.html file with the following content inside:

<!doctype html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body>
  </body>
</html>

This meta tag enforces the user’s web browser to display the website at the correct width of the device. For more information on this tag read this .

Add media queries

Media queries should be added inside your .css files. Create the file style.css and link it inside your index.html file.

body {
  background: red;    
}

@media (max-width: 320px){
    body {
      background: green;    
    }
}

(max-width: 320px)means whenever the the screen size is smaller than 320px change the css.

You could also use (min-width: 320px) and the css would change when the screen size is above 320px.

Orientation

You can also change the css depending on the orientation of the device (portrait/landscape)

Turn your mobile device sideways to see the box color cyan.

body {
  background: red;    
}

@media (orientation: landscape){
    body {
      background: cyan;    
    }
}

Logical operators

Cool but what if we want to use more than one condition? Well we use and or not

body {
  background: red;    
}

@media (max-width: 320px) and (orientation: landscape){
    body {
      background: purple;    
    }
}

Those are the basics of media queries and with them you can design responsive websites. For more on media queries go here .

Thanks for reading!





About List