Sunday, 26 October 2014

Web page layout using CSS

In this post we explore a simple way to give web pages a navigation bar and a fixed-width sidebar.

Elements in a web page are best represented using <div> elements. Here goes:

page.html
--------------
<html>
<head>
<link rel="stylesheet" type="text/css" href="page.css">
</head>
<body>
<div id="navbar">
</div>
<div id="leftpane">
</div>
</body>
</html>

page.css
--------------
#navbar {
position: absolute;
top: 0;
left: 0;
right: 0;
height: 48px;
background-color: yellow;
}

#leftpane {
position: absolute;
top: 48px;
left: 0;
width: 300px;
bottom: 0;
background-color: pink;
}

Note the use of position: absolute and the top/left/right/bottom "anchors". For the navbar, we want the sides of the bar to always be positioned relative to the top, left, and right corners of the web page. The height should be fixed, regardless of page size. Similarly, the sides of the leftpane are positioned relative to the web page and to the navbar.

The best part is that we can resize the browser window, and still achieve the desired visual effect. Try it out!

No comments:

Post a Comment