Thursday, September 6, 2012

HTML5 and CSS for Mobile-aware Liquid Layouts

This is inspired by a talk, given by Rupert Breheny at the Frontend Conference (Zurich). The idea: simple CSS can help layouts adapt to changes in the viewport thus eliminating the need to have different sites for desktop, mobile, and tablet. The goal is to have the content shrink when viewport width gets smaller and re-arrange it from a horizontally aligned (like the three column layout of this example) to a vertically aligned one and avoid horizontal scroll bars.

The code:

The HTML
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>The HTML5 With Mobile in Mind</title>
    <meta name="description" content="The HTML5 With Mobile in Mind">
    <link rel="stylesheet" href="html5mob.css">
</head>
<body>
<div>
This is an example of a markup with mobile in mind.
It is a three-column layout that acts in a resolution-independent manner.
</div>
<h2>Three columns</h2>
<div class="column">
    Column 1<br>
    <p>
        ...
    </p>
</div>
<div class="column">
    Column 2<br>
    <p>
        ...
    </p>
</div>
<div class="column last">
    Column 3<br>
    <p>
        ...
    </p>
</div>
</body>
</html>

The CSS: its the media line that will make sure a different CSS kicks in for smaller viewports.
html {
    background: #7fffd4;
}

body {
    background: #fffff0;
    max-width: 640px;
    margin: 0 auto;
}

.column {
    background: #6495ed;
    width: 32%;
    margin-right: 2%;
    float: left;
}

.column.last {
    margin-right: 0;
}

h1, h2 {
    clear: both;
}

@media screen and (max-width: 480px) {
    body {
        background: #fa8072;
    }
    .column {
        float: none;
        width: 100%;
        margin: 0;
    }
}
Some screenshots:

  • when displayed by a narrow browser:

  • when displayed by a wider browser: 



No comments:

Post a Comment