How to Centre a DIV Block Using CSS
Steps to Centering a DIV Block without Centering the Text Inside
Let's assume that you have a div block as follows:
This is a DIV block that is to be centred. I don't
want the text to be centred, though, just the block.
At first glance, you may think that the following CSS rule will work.
text-align: center ;
However, the rule centres the text inside the box, rather than the block itself. While there are times when you may want to do this, our intention here is to centre the entire block but leave the internal contents formatted as it was before. As such, the above code is not what we want.
Instead, the standard trick to centering a block in CSS is to do the following:
1. Specify a width for the DIV block.
2. Set both its left and right margins to auto.
Both steps are necessary -- that is, you cannot just set the margins to auto without specifying the width of the block and expect this method to work.
The technique works because when both margins are set to auto, web browsers are required by the CSS standard to give them equal width.
For example, if you want your div block to have a width of 700 pixels, the following code will centre the block.
width: 700px ;
margin-left: auto ;
margin-right: auto ;