Learning how to center using CSS is a good idea because the HTML
centering textcentering a block elementcentering an imagevertically centering an element such as a block or image
Centering Text
Centering text using CSS is very easy and straightforward. There is only one property you need to know for centering text. The property is text-align. Here is an example. In this example, any div element that has been assigned the center class will horizontally center the contents of the div. You should note that the text-align property only applies to the text within the parent element. The text-align property does not center align the parent element itself.
Center Block Elements
Centering block elements is also fairly easy to accomplish. The proper way to center a block element is to set a width for the element and also set the left and right margins to auto. Here is an example: As long as the block element has a set width, it will center itself inside its parent element. However, text that is contained in the block will not be centered. If you need the text to be centered as well, just add the text-align property as well.
Centering Images
Ensuring that images are centered across browsers is a little trickier. While most browsers will display images centered using the same text-align property, it is not a good idea. Also, it is not recommended by the W3C. Instead of using the text-align property, you should use apply the display property to the image and set the display to block instead of displaying the image as inline. Once the image is treated as a block, it is easy to center it as we did in the earlier example. Here is an example: Any image element that you assign the center class will be centered horizontally inside the parent element.
Vertically Centering Elements
The current version of CSS (version 2) does not have explicit support for centering items vertically on the page. There are a few ways to get around this problem, but it does not work well with versions of Internet Explorer earlier than 8. The W3C recommends you approach this by using this technique: The trick is to specify that the block is formatted as a table cell because the contents of a table cell can be centered vertically. Keep in mind that results may vary depending on the browser. We can expand on this and include some of the other properties that have been covered in this article if we need to also horizontally center the element on the page and its contents. If you want to horizontally center the div, just place this div within another div and horizontally center the outer div using the width and margin technique discussed earlier.