Archive for January, 2010

Centering a block using CSS

Many times, I’ve found myself in the need of a solution to center a block in a webpage. This problem is complicated if the parent block has a variable width, for example, when the parent block is body. In the past, I used the trick of negative margin. For example, if the block has a width of 500px, I would do:

.centered-block {
  margin-left: -250px;
  left: 50%;

The negative margin puts exactly half the block off the left border of parent block, effectively aligning the center of the block at the left border of the parent block. Moving the block to the right by 50% will now place the center at the center of the parent block. The combination effect of the two is that the block is center aligned to the parent block.

I sometimes see undesired horizontal scroll bar when using this method, possibly due to the last line in the CSS code, which could potentially increase size of the canvas.

I have found a better solution that uses inline-block. The corresponding code for the above scenario using inline-block can be:

.parent-of-centered-block {
.centered-block {

Using this method, I have never seen undesired horizontal scrollbar. There is an extra benefit. You could now eliminate the width property if you want the centered block to have a flexible width, meaning it can be as small as possible but grow when necessary to accommodate content in one line if possible. In one of my cases, I wanted to place a line of several icons in the center. I removed the width property, and let the block to figure out its best width by trying to put all icons on the same line. See it works in a real case.

Read Full Post »