Mobile Style Sheet

Finally, this blog’s layout flows better on a mobile device with a smaller screen. If something’s off, tell me in the comments 🙂

Here are some CSS rules that I’ve found to be quite useful for mobile devices:

This tells your smartphone that you have thought about its smaller screen size and you don’t want it to fit everything onto its screen as a PC would:

<meta name="viewport" content="width=device-width" />

Import your mobile style sheet after all your other styles so you can override them.

<link href="css/mobile.css" rel="stylesheet" media="screen and (max-width:768px)" type="text/css" />

This is an alternative way you need to use inside a .css file or style-tag:

@import url("css/mobile.css") screen and (max-width:768px);

You don’t have to define a minimum width for your page but if you do (I wanted the menu bar to wrap after a specific menu item) do it in em units so it’s relative to the font size.

body {
   min-width: 30em;
}

For your mobile device, you probably want to reset some horizontal margins and paddings to make the most out of the small screen. These are keywords to reset stuff if you have defined specific pixel, em or percentage values. Also, floating elements horizontally might also not look good on small screens.

width: auto;
margin: 0;
padding: 0;
float: none;

Keep in mind that an element’s CSS rules are applied according to priorities. The more specific a rule is the higher its priority and an override for it must have at least the same priority. Consider this example of a margin on a paragraph inside what could be two layout-specific div containers (the main one with an id tag called ‘content’, the nested one with a class tag called ‘blogpost’):

#content .blogpost p {
   margin-left: 2em;
}

This rule will not reset the margin since it is not as specific as the original style definition:

p { margin: 0; }

You need to use either one of these. Although using ‘!important’ might seem like an easy solution it should be used sparingly since it will override a lot of things that you didn’t intend:

/* be at least as specific in your override */
#content .blogpost p { margin: 0; }
 
/* or force this rule onto every paragraph */
p { margin: 0 !important; }

Large images are a problem because they will force the smartphone to increase the page width which results in a smaller font or the need to scroll horizontally. This snippet, which is even useful for your blog’s regular style sheet, scales down images dynamically to fit the available width of its parent container:

img {
    /* auto-fit images to column width */
    max-width: 100%;
    height: auto;
}

Tags:

Comments are closed.