5 November, 2013 — Development

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?

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:

#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 useful for you! If you have any comments or suggestions, do not hesitate to post them in the comments section.

Photo Credit: Zzpza