24Changing Looks with Nested @media

Sometimes we’d like to change what is displayed based on the device on which the content is being displayed. CSS2 introduced the concept of @media. Various attributes, such as print, handheld, or tv can be used to define different property values, such as font sizes, depending on the medium used to view the page.

The main flaw with @media is that it can’t be nested. Say you want to have all the main areas in 15px font, except for when you print the document. In CSS, you’d have to copy out all the declarations again.

Sass to the rescue! We can just add in another declaration specifically for one type of media, and it’s compiled into a whole new selector when the CSS style sheet is made.

This is particularly useful in the era of the mobile web. The handheld attribute should alter the page if it’s being viewed on a handheld device. However, a lot of phones don’t currently seem to support it. There’s a neat trick around this: use a maximum screen width. We’ll use the iPhone as an example.

We know that the maximum width of the iPhone screen in portrait mode is 320px. We can just add this on to the end of our @media! Using it in a nested style allows us to say that the font should be larger only when the screen is at a maximum of 320px wide. When this is the only change we need to make, it’s SO much easier than having a whole separate selector.

Added bonus: for landscape, we choose a minimum width of 321px and a maximum width of 480px.

What To Do...
  • Use @media in a nested style.
    advanced/atmedia.scss
     
    .main {
     
    color: #336699;
     
    font-size: 15px;
     
    @media​ print {
     
    font-size: 10px; } }

    This compiles to:

     
    .main {
     
    color: #336699;
     
    font-size: 15px; }
     
    @media​ ​print​ {
     
    .main {
     
    font-size: 10px; } }
  • Make your sites portrait-specific…
    advanced/atmedia_phone_portrait.scss
     
    .main {
     
    color: #336699;
     
    font-size: 15px;
     
    @media​ screen and (max-width: 320px) {
     
    font-size: 35px; } }
  • …or landscape-specific.
    advanced/atmedia_phone_landscape.scss
     
    .main {
     
    color: #336699;
     
    font-size: 15px;
     
    @media​ screen and (min-width: 321px) and (max-width: 480px) {
     
    font-size: 25px; } }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset