How to Manage Your Webpage’s Layout with CSS

Published March 2, 2015 by saurav.roy.

Before CSS was out, people used tables in order to layout their webpages. Now, the introduction of CSS changed all that. CSS provides us with a lot of flexibility to position the elements in a webpage. In this tutorial we’re going to dive into the two main CSS properties used to defining layout of webpages: the position property and the float property.

The position CSS property
The position property is primarily used to define how an element is treated in the flow of the page. There are four main values that could be used with the position property.
static: The default value of any element. This value renders the element in its normal order as it appears inside the HTML.
relative: This is similar to static but the element can still be moved from its original position with the properties top, right, bottom and left.
absolute: This option removes the element out of the normal flow of the HTML and lets you control its position with top, right, bottom and left.
fixed: This value pretty much behaves absolute but it will also position the element in reference to the browser window and not the webpage. So the fixed elements always stay where they are on the screen even when you scroll the page.

With those options in mind we can create a two column layout easily with absolute positioning if we have something like the following HTML:

 <div id="navigation">
        <li><a href="#">Link1</a></li>
        <li><a href="#">Link2</a></li>
        <li><a href="#">Link3</a></li>
	<li><a href="#">Link4</a></li>
 <div id="content">
    <h1>Header of Column2</h1>
    <p>Some Text inside column 2</p>

By applying the following simple CSS:

#navigation {
    position: absolute;
    top: 0;
    left: 0;
    width: 200px;}
#content {
    margin-left: 200px;}

We will see that this will set the navigation bar to the left and set its width to 200 pixels. Because the navigation is absolutely positioned, it has nothing to do with the flow of the rest of the page. All that is needed is to set the left margin of the content area to be equal to the width of the navigation bar.
Isn’t that easy? And the good news is we’re not limited to this two-column approach. With clever positioning, we can arrange as many blocks as we like. If we wanted to add a third column, for example, we could add a “navigation2” block to the HTML and change the CSS to:

#navigation {
    position: absolute;
    top: 0;
    left: 0;
    width: 200px;
#navigation2 {
    position: absolute;
    top: 0;
    right: 0;
    width: 200px;
#content {
    margin: 0 200px;

The only downside to absolutely positioned boxes is that because they live in a world of their own, there is no way to accurately determine where they end. If we were to use the examples above and all of our pages had small navigation bars and large content areas, we would be okay, but, especially when using relative values for widths and sizes, we often have to abandon any hope of placing anything, such as a footer, below these boxes. If we wanted to do such a thing, one way would be to float the divs, rather than absolutely positioning them. Which brings us to the second part of our tutorial.

The float CSS property
Floating a box will shift it to the right or left of the container div, with any surrounding content flowing around it.
Floating is normally used to shift around smaller divs within a page, some navigation links to the right of the container, but it can also be used with bigger divs, such as navigation columns.

The float property takes only two values, either float:left or float:right.
Using the same HTML we wrote earlier, we could apply the following CSS:

#navigation {
    float: left;
    width: 200px;
#navigation2 {
    float: right;
    width: 200px;
#content {
    margin: 0 200px;

However, floating introduces a small problem with container boxes. That means, if you have a container with all floating elements inside it, the container box won’t wrap around the boxes. Its height or width won’t increase to take the full size of the floating elements inside. Luckily, there is a fix for that, the clear property.

clear:left; will clear left floated boxes
clear:right; will clear right floated boxes
clear:both; will clear both left and right floated boxes.

Adding an extra div inside the container with the CSS property clear:both will clear the floating elements and allow the container to wrap correctly around them. So if, for example, we wanted a footer in our page, we could add a footer div in the HTML as follows:

<div id="footer">
    <p>Footer Text</p>

and then add the following CSS

#footer {
    clear: both;

There we have it! A footer that will appear underneath all columns, regardless of the length. Hope you enjoyed this tutorial. Check this codepen for a full preview.

Embedding Video in a Responsive Site

Published January 23, 2014 by saurav.roy.

We live in the future, and one of the benefits of our brave new world is the thousands of cat videos that are just a click away. Let’s say you’ve just found the perfect felicitous feline video to share with all your friends. You post it to your fancy responsive website quick as a flash (because it’s the future and we can do that), but whoops: the video doesn’t fit! It’s too wide, too narrow, or just awkwardly sized.

Let’s fix that.

First off, we’ll need some sort of a wrapper container for our video. We’ll paste our embed code inside this wrapper. It’ll look something like this:

This wrapper will become our responsive container, adjusting to the size of its parent and allowing us to resize the contents within it. Read On…

Cross-Browser Rounded Buttons with CSS3 and jQuery

Published April 22, 2010 by saurav.roy.

So here’s the scenario: I was tasked with replacing several dozen Photoshop-generated rounded buttons for a larger site with an HTML/CSS/JS equivalent. Prior, any time anyone wanted to change text on a button (and it seemed to happen often), a graphic designer had to fire up Photoshop, modify a file, adjust for size, output an image, and pass that file off to the person building the page. It was an involved process for something that should have been simple.

So let’s make it simple!

Right away I knew that I wanted to present as simple a solution for the developer as I could. I didn’t want to force them to use tons of extra markup in their HTML to pull this trick off. This was a piece of cake in modern browsers, as you’ll see in a moment. Unfortunately, this site also has a large IE user base, so I needed to account for less-modern browsers as well.

Border-Radius for Those Who Can

I decided I wanted to use border-radius for the rounded buttons for any browsers that could support it. I also decided that I wanted to create a single class, “button,” for any buttons, and it should work more-or-less the same on anchor tags, button tags, and “submit-type input tags. Read On…

Understanding the CSS Float Property

Published March 18, 2010 by saurav.roy.

I want to take a moment today and talk about CSS floats. They’re used everywhere in modern web design, from navigation bars to building CSS columns and dozens of techniques in between. However, despite their prevalence, not everyone understands exactly how they work, or what the repercussions might be from using them. So let’s remedy that. You can see all the examples from this article here. Read On…

CSS Art: The Flower

Published February 23, 2009 by saurav.roy.

css art flower

Today’s article is probably not the most practical tutorial I’ve ever written, but it was definitely one of the most fun to create. It also shows that, while CSS is often treated as a straightforward web development workhorse (and it’s a great workhorse, at that), it can also have a lighthearted, eccentric side as well. Today’s tutorial is about how to use CSS to create art.

Now, as I’ve mentioned numerous times, I am not an artist. If true CSS artists were likened to Salvador Dali or someone similar, I’d be more akin to the guy watching Bob Ross on public television and following along at home, creating wobbly little smudges and pretending they’re happy little trees. But! What my example above (and you can skip ahead and see the final version) shows is that it doesn’t take very many CSS rules to create some pretty cool CSS art. Read On…

jQuery-Based Popout Ad: Part 1

Published September 9, 2008 by saurav.roy.

Advertisements on the web: love them or hate them, it’s safe to say they’re here to stay for a good long while. But advertising is a tough line to walk for a lot of websites (such as this one). Make your ads too annoying, and you’ll lose readership. But make them too unobtrusive, and you might as well not even have them at all. So where’s the balance?

Today I’d like to start an article series of three parts, the result of which will be a popout-style, jQuery-based box like the one pictured above, which I think strikes a nice balance on the obtrusion-scale. A friend of mine and I first developed this box to contain advertisements, but it’s a pretty versatile little technique: we’ve also used it to hold signup forms, and it could be expanded to other uses fairly easily.

If you’d like to see this popout ad in action, click here.

So what’s the benefit of this little popout box? First of all, it’s pretty simple to set up. In today’s article, I’ll cover the XHTML and CSS necessary to build this popout box, and you’ll see that it doesn’t take as much code as you might expect.

Second, it’s an eye-catching, yet not entirely annoying, technique. The ad opens after the page loads, which tends to draw the reader’s eye that direction. But if the ad isn’t for them, they can just click the close button and move it out of the way. Part 2 of this series will cover the jQuery used to make the ad function as prescribed.

Third, the technique easy to customize for your specific needs. In part 3 of this series, I’ll cover adding cookie support (to remember whether the ad should be open or closed) using a great jQuery plugin, generalizing your CSS to support both left- and right-aligned boxes with just one stylesheet, and even supporting multiple ads on the same page, should you decide to push the envelope.

Intrigued? Great! Let’s dive in to part 1.

The Images Required

Depending on how you’re using the box, you’ll need some images. For mine, I’m using two images. The first image functions as the ad “cap,” which is permanently affixed to the side of the page. Clicking this image will, once we’ve added our jQuery, cause the ad itself to open and close.

The second image is simply for the advertisement itself. Depending on your ad source and type, this image may or may not be necessary. If you’d like to follow along at home, you can download the image files I’m using here (Photoshop files and GIF/PNG images included).

Writing the XHTML

The XHTML is fairly simple, only requiring a few divs, images, and anchors:

<div id="popout">
	<div id="cap">
		<a href="#" id="open">
			<img src="images/cap.gif" width="20" height="350" alt="Open the Ad." />
	<div id="adbox">
		<a href="#" id="close" title="Close this ad.">
		<a href="#" id="ad">
			<img src="images/ad.png" width="300" height="330" alt="" />

The main div, “popout,” acts as a wrapper for the whole shebang. It contains all the other elements, and comes in handy when writing our jQuery and our CSS.

Next up comes the “cap” div. Technically, this div isn’t even 100% necessary — you could just as easily attach your CSS and jQuery scripts to the anchor tag it contains. But I find it’s useful to think of the cap as a wholly distinct unit from the advertisement, so I’ve put it in a separate div to help me think of it as such.

Inside the cap div is an anchor, “open,” which in turn contains the image of our cap. The anchor tag serves a critical role: it’s what we use in our jQuery later on to trigger the opening and closing of the ad.

After the cap comes the “adbox” div, which contains the real guts of our popout ad. First up is the “close” anchor, which functions as a close box. As you can see from the image above, I’ve built a close box into my ad itself: if you preferred, you could make the close button a standalone image and absolutely position it over your ad… but for the sake of simplicity in this tutorial, I’ve chosen not to here.

And finally, we have the “ad” anchor, which contains the advertisement itself. I can get away with just an anchor and an image because I’ve developed this ad myself, and am hosting it locally. If you were using a different ad type, such as one that were pulled in dynamically using JavaScript or the like, you’d put that code here instead (probably wrapped in a div to keep it contained).

And that’s all the XHTML you’ll need! So let’s move on to the CSS.

Adding the CSS

The first thing we need to do is establish our containing popout div on the page:

#popout {
	margin: 0;
	padding: 0;
	width: 320px;
	height: 350px;
	position: absolute;
	top: 200px;
	left: 0;
	z-index: 100;
	overflow: hidden; }

The first couple of rules simply nullify any margins or padding that might be hanging around in other places in your CSS: the last thing we need is a rogue rule crimping our style. If you’re sure none exist, you can eliminate those lines.

Our width and height rules are pretty simple: they state the height of the ad (which in our case is actually the height of the cap, as our ad is slightly shorter) and the maximum width the ad will take up (when the ad is closed, it takes up much less space).

Next up, we’re positioning the ad on the page. These rules are useful for two reasons. First, it allows us to position the ad wherever we want on the page. I’ve chosen to start the ad 200 pixels down on the left hand side, but you can really place it wherever you want. Second, positioning the popout wrapper allows us to absolutely position elements within that wrapper, which will come in handy shortly.

We finish up with two less common rules: z-index and overflow. The z-index is helping to ensure our ad is on top of any other content on your page: elements with a lower z-index (1 is the default) will show up below our wrapper. The overflow rule doesn’t do a lot for us initially, but is critical for our jQuery to do its magic. We’ll cover that in part 2.

With our popout wrapper in place, we can start styling its innards, starting with some general rules:

#popout a, #popout a img {
	text-decoration: none;
	border: 0;
	outline: 0; }
#popout a span {
	display: none; }

The first set of rules ensures that none of our anchors or images have any borders, outlines, or underlines from our anchors and the images they contain. Normally you wouldn’t want to eliminate any sign that something had been or could be clicked, but because this is an advertisement we’re building, I think we’re allowed to bend the rules of usability for the sake of aesthetics. If you disagree, feel free to remove that rule.

Next up, we’re setting a general rule that comes in handy for me: any span within anchor tags will be magically disappeared. In our example, this only pertains to the “Close” text inside its corresponding anchor, but in theory you could have more text in your popout wrapper that you’d want to hide. For example, when building these ads I often load the cap image as a background image and have text inside of the anchor.

With the generalities out of the way, let’s start in on specifics, starting with the cap:

#popout #cap {
	width: 20px;
	height: 350px;
	position: relative;
	left: 0;
	z-index: 102; }

Pretty basic stuff, huh? We’re setting a width and height first, which just ensures our div doesn’t take up any more space than is necessary. Then, we relatively position the ad. This is mostly done so that we can specify a z-index. Our z-index here says that we want it to be even higher than the popout ad; and you’ll see why shortly.

Next up, we position our close button:

#popout a#close {
	position: absolute;
	top: 0;
	background: transparent url(transparent.gif);
	left: 240px;
	height: 20px;
	width: 60px; }

Here, we’re absolutely positioning the close button in the top-right corner of our popout wrapper div. If you’ll recall, the top-right corner is where I’d placed the close button in our image. This just ensures the close button is in the right spot, even though its contents were rendered invisible by that previous display:none rule. But you’ll notice that I’m using the “left” property to push our button right, instead of just positioning against the right-hand side with the “right” property. This is to take into account a bug in Opera that causes our close button to be positioned improperly when aligned along the right-hand side of our animated box (you can read all the juicy details in the comment thread of part 2 of this series)

I’m also specifying a height and width — be sure to adjust yours to the size of your close button. Technically you could use a percentage or em value for the width, but I’m using pixels to make the math involved in pushing it from the left easier.

I’ve also added a fix to the CSS above to take care of an Internet Explorer bug. IE shrinks the clickable area of an anchor tag to be the size of its content, even if we’ve specified a width and height that gives the anchor a different size. Because we are hiding the content of this anchor using a “display: none” rule, this means the anchor is effectively unclickable in Internet Explorer. However, IE does recognize the size of the link if it’s filled with a background image. Thus, by adding a transparent background image to our anchor (I’m using a 1×1 pixel transparent gif), the size and shape of the anchor is respected.

And finally, we’re ready to position our advertisement itself:

#popout #adbox {
	position: absolute;
	top: 10px;	
	left: 20px;
	z-index: 101; }

Our position of absolute allows us to move the ad right into position: 10 pixels from the top of the popout wrapper (because my ad is 20 pixels shorter than the cap, this centers it nicely) and 20 pixels from the left (which happens to be the exact width of the cap). And finally, we’ve set a z-index of 101, which is 1 less that the z-index of our cap. This means that our cap is “above” our ad — when we use jQuery to animate the ad in part 2, this will come in handy, allowing us to slip the ad behind the cap.

And that brings us to the end of part 1. You can see the results of our efforts (without any jQuery magic) here. Stay tuned for parts 2 and 3, when things really start to get fun!

Note: Part 2 of this series is now available here. And when you’re ready, part 3 is available here.

An Argument Against Faux Absolute Positioning

Published June 28, 2008 by saurav.roy.

A week or so ago, Netherlands-based Eric Sol published an article on A List Apart titled “Faux Absolute Positioning,” where he outlines a new system of element positioning that he has developed. Shortly afterwards, a reader wrote to me and asked my opinions on the technique. In the spirit of continuing the fantastic conversations we’ve been having on CSSnewbie recently, I thought I would respond publicly so that others might have the option of offering their opinions as well. But if you haven’t read Eric’s article yet, please do so before responding, so you have the full picture and not just my interpretation of things.

Mr. Sol’s development of the Faux Absolute Positioning technique was born of frustration in trying to use the two dominant positioning techniques: absolute positioning elements, and floating elements. His argument against using absolute positioning for page layout is that it causes any containing elements to collapse (because the element is pulled out of the document flow), which can cause all sorts of problems. This, I will entirely agree with.

However, his argument against using floated elements is that content changes can cause the width of the element to change, which can in turn wreak havoc on float-based layouts. This is partially true. Left to its own devices, for example, a 500 pixel wide column containing a 550 pixel wide image will probably ruin a float-based layout. However, in practice simply applying a rule of “overflow: hidden” to that column would have eliminated any column-resizing problems in nearly all cases, simply cutting off the side of the image when it reached the edge of the column. And considering that using Faux Absolute Positioning relies on an understanding that “the content of the boxes may overlap,” but that “it’s better to risk overlap than risk breaking the whole layout,” I don’t understand what makes using “overflow: hidden” on floated elements so detrimental or different.

But that isn’t my real concern with Eric’s argument for the technique. I’m most concerned with the XHTML structure required to actually implement the technique. As I’ve mentioned before, I’m a bit of a code purist. I believe in using the least amount of code to the greatest effect, and this is especially true when it comes to XHTML. A CSS file can be cached and reused by the browser over an entire website, reducing the strain on a user’s bandwidth. However, each new page a user visits requires them to download an entirely new XHTML page, regardless of how similar that page is to the previous one they visited. In my mind, this is the strongest argument behind switching from presentation-heavy HTML (tables, font tags, etc) to semantic XHTML (and using CSS for presentation) in the first place.

Because of that, I wince when I see the XHTML used to implement the Faux Absolute Positioning technique. Take a look at the sample offered:

<div id="canvas">
  <div class="line">
    <div class="item" id="item1">
      <div class="sap-content">content here</div>

Does that structure look strangely familiar? It should – it’s a table, converted into divs. The “canvas” div functions as the table container, while the “line” class of divs acts as rows and the “item” divs behave as table cells. In fact, this technique actually uses an additional div (“sap-content”) inside of each “cell,” bloating the code even further. Compare it to this table-based reimplementation:

<table id="canvas">
  <tr class="line">
    <td class="item" id="item1">
      <div class="sap-content">content here</div>

Now, I understand that there is a semantics argument to be made here. Mr. Sol probably didn’t want to use a table because, semantically speaking, a table should contain tabular data and nothing more. But the problem is, the Faux Absolute Positioning technique simply reimagines tables using divs and classes rather than “tr” and “td” tags.

The real benefit of the technique, Eric states, is that “we can align every item to a predefined position on the grid […] but items still affect the normal flow,” and his insistence on thinking of elements in a page as “cells in [a] grid” is telling: the author really just wants to use a table, but can’t justify it semantically. Thus, he develops a “semantic” alternative that, instead of suffering from non-semantic code, suffers from divitis, classitis, and code bloat instead.

I wrote an article a couple of weeks back on building a calendar using lists instead of tables that ended up sparking a great deal of thoughtful debate of the nature of calendars, the semantic meaning of tables, and the overuse of lists in modern web design. I plan to respond to that debate more fully next week in a separate article, but one point I plan to make then is worth mentioning now: I believe in using semantic code wherever possible, but I also believe in minimizing code wherever possible. One of the (several) reasons I was so intrigued by the possibility of a list-based calendar is that I knew I could create it with less XHTML than a table-based calendar would require, reducing the bandwidth costs of whatever website it was implemented on.

The Faux Absolute Positioning technique, by contrast, requires at least as much XHTML as an equally complex table would require, and may actually require significantly more code because of the additional div inside each “cell.” Depending on the complexity of the site using this technique, we could be talking about 15% greater bandwidth costs on every single page of the website, compared to an identical site using a table for layout. Admittedly, the website could still tout a “table-less” design, at least in the narrowest definition of the phrase. But because of its insistence on rows, columns, and a clearly defined grid, it is at least a table in spirit, and may in fact be more complex and weighty than a table would be in practice. And if a designer is utterly committed to having the rows, columns, and cell-based grid that this technique permits, I would argue that the table tag deserves a second look, if for no other reason that to reduce page size.

At the end of the article, the author does admit that this technique is probably only sufficiently rewarding to be used on rather complex page layouts. But if a site’s layout has reached the level of complexity wherein the only viable options are to use a table to create a grid or reinvent a table to the same end, perhaps it’s the design of the site, and not the code behind the site, that should be reconsidered.

Now, I don’t want to be seen as attacking Mr. Sol’s person or work. I respect the amount of time it must have taken to develop the Faux Absolute Positioning technique and the ingenuity that went into the CSS. My goal here is to simply encourage a debate on the subject. And now that I’ve had my say, I would love to hear what you think about all this.

Harnessing CSS Positioning: Part 1

Published March 26, 2008 by saurav.roy.

racehorse in mid-run

Earlier this week, I explained the basics of CSS positioning: what it is and what your options are. Now I’d like to take some time and explain a couple of tricks for using positioning in the real world… stuff that really harnesses the true power of CSS positioning.

Absolute Positioning Inside Relative Positioning

One of the coolest and simplest ways to harness the power of positioning is to use a combination of relative and absolute positioning. Specifically, to absolute position an object inside of a relatively positioned object. Why is this so cool? Because of one of the under-understood rules of positioning.

Any time an element is absolutely positioned, it’s actually being positioned according to the boundaries of its containing block. By default, with no other objects positioned on the page, the containing block is the <body> tag. However, if you position any element further down in the hierarchy (like a containing div, for example), that positioned element becomes your new containing block. What’s that mean in practice? It means you can have some XTHML that looks like this:

<div id="wrap">
	<p>This stuff is in the wrapper</p>
	<div id="sidebar">
		<p>Sidebar information is cool</p>

Then, you can size and relatively position your wrapper div, like so:

#wrap {
	width: 500px;
	margin: 0 auto;
	position: relative;

Here, all we’re doing is giving it a width, centering it with an auto margin trick, and then setting a relative position. But we’re not actually moving the div anywhere! Setting a relative position, but then not setting a top, bottom, left or right property means the element doesn’t move anywhere. But, because it has a “position” set, it becomes our new containing block. Now, we can specify styles on our sidebar that look something like this:

#sidebar {
	position: absolute;
	top: 0;
	right: 0;

As we learned last week, setting our top and right properties to zero, with an absolute position, should move our sidebar to the top-right of the page. However, because our wrapper div became our new containing block through use of the relative position, the sidebar is actually just moved to the top-right corner of the wrapper div. This can be extremely useful when you have a fixed-width and centered web page: you may want to absolutely position elements according to your “page,” but not according to the browser window. This is how that’s done. You can see a slightly more involved example here.

Fixed-Position Navigation

If you have a website that tends to be a bit on the wordy/lengthy side (like, erm… this one?), it could be useful to ensure that the site’s navigation is always at the top of the page, no matter how far down your users scroll. For that, fixed positioning can really come in handy.

For this trick, all you need to do is develop a navigation bar of some sort (covered in more detail here), and then “fix” it to the top of your website. You’d start out with some XHTML like this:

<div id="wrap">
	<ul id="nav">
	<h1>Page Title</h1>
	<p>This page is cooler than it looks.</p>

Next, you’d want to pull your “fix” your navbar to the top of the page:

#nav {
	position: fixed;
	top: 0;

And really, that’s the meat of your code. The fixed position tells the browser to pull the navbar out of the normal document flow, and then affix it to the top of the page. Of course, because it has been taken out of your document flow, the navbar might be overlapping your text, which will move up the page to fill the space that the navbar has vacated. To ensure that doesn’t happen, you’d want to add some space to the top of your website. Something like this would do the trick:

#wrap {
	/* Your padding should be the height
	of your navigation bar, plus the 
	space you want between the navbar
	and the top of your page. */
	padding-top: 50px;

As the comment above states, you’ll want to add enough padding to compensate for the height of your navbar, as well as any extra spacing you want between your navbar and the content below. So if your navbar were 30 pixels tall, and you wanted 20 pixels of space before you got to your header, you’d want 30 + 20 = 50 pixels of space at the top.

And voila! You now have a navigation bar perma-fixed to the top of your browser window. No matter how far down your page your users scroll, your navigation will never be more than a few pixels away. You can see it in action here.

These are just two ways in which the position property can really make your life easier, your websites cooler, and your wife more satisfied. Stay tuned, because next week I’ll show you a couple of other neat positioning tricks: one for creating big visual impact with absolute positioning, and another for making subtle (but useful!) text changes using relative positioning.