float:center

Unfortunately float:center is not valid CSS, no matter how much we would like it to be. And God knows I tried. The thing with floats is that the left and right property really make them go to the left of their (floating) container. The problem you can get in to is with a series of boxes that you want to have floating alongside, and then centered in the middle of the site.

Let’s say for example you want to have three buttons next to each other, spread out over the full width of your site, and they all link to some section of your site, say:

  • My Portfolio
  • About CSS
  • Blog

In addition, you want it to be viewable on a really small screen, as a PDA or phone browser, and the easiest way you think would be to put them floating, so they would automatically wrap. This is usually a good idea, however, in this case you also want the buttons to be smack left aligned when viewed on a small screen.

There just is no solution for that. The only thing that comes close is giving all these buttons a fixed width (don’t get me started on percentages, it just won’t work). Make sure the sum of the widths equals the width of the container. So if I have a site of 660px, I would give every box a width of 200px and add 10px padding on every side of each box.

So

  • Box A: 10+200+10 = 220px
  • Box B: 10+200+10 = 220px
  • Box C: 10+200+10 = 220px

The only problem is that when you make the window smaller the boxes all have a little indentation on the left.

This is the CSS you would use

.container {
  width: 660px;
  margin:0 auto;
  display:block; }
.button {
  width:200px;
  padding:10px;
  background-color: gray;
  border:1px solid black; }

Of course you could do the same thing with ems.

Update: this problem was recently solved by Firefox 3.0. As of this version all major browsers, including IE6 have support for inline-block. When you use inline-block, you don’t need floats. Put it on the boxes (as in the above example Box a,b and c). You don’t have to specify a width, and by putting text-align:center on the container the boxes will automatically be centered, no matter how many boxes you have.

Advertisements