Posts Tagged ‘CSS’

float: center

July 9, 2008

As a CSS enthusiast, one of the questions I have heard a lot over the past few years has been, “How do I float center?” To that, I have always replied simply, “you don’t,” and then I delve into what my colleague is actually trying to do. (Really, when was the last time you wanted content to flow around both sides of a block?)

Today my answer has changed.

Here are three block-display elements.
There are no explicit widths set.
Siblings have the same effective width and are centered.

Alternatives

First off, let’s not use a cannon to kill a mosquito. If you need to center a single line of text (styling not withstanding), just set text-align: center on the containing block. If you really need to center a block, set its left and right margins to identical values. If your block has an explicit width, set the left and right margins to auto.

What if you do not have (or desire) explicit margins or an explicit width? What if you want several sibling blocks to have the same width? I’m glad you asked…

The simple, three-step process

Consider the following HTML fragment in this example.

<div class="rowWrapper">
	<div class="row">Here are three block-display elements.</div>
	<div class="row">There are no explicit widths set.</div>
	<div class="row">Siblings have the same effective width and are centered.</div>
</div> 

For the sake of the example, I’ll give the wrapper a red border and the rows a blue border.

Here are three block-display elements.
There are no explicit widths set.
Siblings have the same effective width and are centered.

1. Float the wrapper

.rowWrapper {
	border: 1px solid red;
	float: left;
}

Wrap your blocks and float the wrapper. Because your blocks are in normal flow, they will each have the same width by expanding to fill their parent block. Because the parent block is floated, it will have the minimum width necessary to contain the child blocks. This results in the following:

Here are three block-display elements.
There are no explicit widths set.
Siblings have the same effective width and are centered.

2. Position the wrapper

.rowWrapper {
	border: 1px solid red;
	float: left;
	position: relative;
	left: 50%;
}

This centers the left edge of the wrapper, and thus your soon-to-be-centered, now equal-width blocks.

Here are three block-display elements.
There are no explicit widths set.
Siblings have the same effective width and are centered.

3. Position the ‘rows’

.row {
	border: 1px solid blue;
	position: relative;
	left: -50%;
}

This puts the center of the equal-width blocks at the left edge of the wrapper.

Here are three block-display elements.
There are no explicit widths set.
Siblings have the same effective width and are centered.

Naturally, you’ll want to remove any visible signs of the wrapper.