Center a block element without knowing its width

Centering an element may seem quite simple thinking that “text-align:center” will solve the problem. Or maybe set “width” and “margin: 0 auto”, but what happens when you need to center a block element with variable width?

In this article you’ll learn how to center a block element with variable width.

By default div has auto width

W3C tells us that we can use “margin: 0 auto” to center tables so why shouldn’t we use display: table to center a fluid div:

div.my-element
{
  display: table;
  margin: 0 auto;
}

This can solve many problems and does a good job in some cases but you must be aware that “display: table” is not working when using our “beloved” Internet Explorer (IE5.5, IE 6, IE 7) so don’t count on this for main design elements (especially if this ruins your design).

I hope this was usefully for you! If you have any comments or suggestions, do not hesitate to post them in the comments section.

If you enjoyed this article, you might also like:

Written by Catalin Rosu

Catalin Rosu, a.k.a Red, is a passionate web designer and developer who loves to be creative and enjoys CSS techniques. Stay tuned for latest updates, subscribe to RSS and follow him on Twitter.

One Response to “Center a block element without knowing its width”

  1. Denis says:

    Great article!
    This is awesome! thanks! :)

    but a little question…………… and for ie?

    I’ve to put a div inside another div with “width:100%”! Is it correct? Is there another hack?

    Thank u! Have a great day!!

Leave a Reply