How To Center A Block Element Without Width Defined

It is simple to center an element with its width defined but the real issue crops when we are faced by the challenge of centering the block element for which we don’t have any width set.

How To Center A Block Element Without Width Defined

Say for example we have a div or any other block element for which we have given width:auto. Now the element will spread across the browser window.

center block

Our aim is to center the element and spread it as per the content it contains.

center block01
How do we do it?

Html to use:

<div> Lorem Ipsum is simply dummy text of the printing industry.</div>

Css to use:

  display: table;
  margin: 0 auto;

These are the two most important properties that solve our problem.

Let’s see what these properties mean:

1. Display: table – The element is displayed as a table with this CSS property.

2. Margin: 0 auto – By giving value 0 in the first spot the element is cleared of area around from top and bottom. And giving auto in the second spot will position the element in the center creating equal gaps from left and right side.

Yes margin:auto is used to center an element but when we know the width. Here it won’t solve the issue as we know that we don’t have width defined to our block element.

It’s the combination of these two properties which will help us achieve our goal.

Tip: You should also use background, border properties to identify the element.

IE 7 and below

This technique will center the block element but the problem with this is that
IE (IE 7 and below) do not support it.

Final Words

If you are not supporting IE then you will not face much of an issue. But avoid using the trick if you are going ahead and want your design to look proper in IE.

Please share your thoughts and experience…


Written by Nikhil Malhotra

Hi! I am Nikhil Malhotra, a Web/UI designer and Front End developer. This is the area of my website where I share my knowledge in form of tutorials and articles.

This entry was posted in Code and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *