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.

Related content

Written by Red

Catalin Rosu, a.k.a Red, is a professional 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.

Leave a Reply