There are several clever ways to center text in HTML or at least simulate that text has been centered. For the purpose of this guide, we have left out these clever hacks and focused on the features that were designed to do this.
We will therefore be looking at two major ways that you can center text in HTML. The first includes using the HTML tags and HTML attributes on block elements, The second uses the more preferred CSS properties.
These methods will affect not just text but other elements such as images, video, other containers and objects depending on the element that is being centered and whether it supports child elements or not.
Center Text in HTML Without Using CSS
The first is using the deprecated <center> tag. It was deprecated in HTML 4 and should not be used. We are making mention of it for those still using HTML 4.x and just for historical purposes. This tag does not work in HTML5 as you a would expect. The tag can be used as a custom HTML5 container and can be styled accordingly using CSS. So please do not use it.
The second method we will see here is using the deprecated align attribute of block tags such as <div>. Again this was deprecated in HTML 4 and will not work in HTML5. We have gone and included it here for the same reasons as the <center> tag.
Using the Modern CSS Methods
1. Inline CSS
The first method we will look at involves using inline CSS directly into the HTML tags. This method is not recommended because it is somewhat of a maintenance nightmare in more practical website projects. Best practice states that designers separate CSS from HTML and contents. Nevertheless it is perfectly legal to use it and beneficial in some scenarios. One such reason you would want to use inline CSS is when formatting HTML emails. This method takes advantage of the style attribute in HTML tags.
2. CSS in Style Tags
It may be more efficient to style multiple blocks with a single rule. In this case inline CSS may not be ideal So you would need to place your styles in an external CSS file or in <style> tags in the head of your HTML page. You can either style the tag by tag name, by class name or by id as shown below.
In practical terms the rules above will override the previous ones if they are applied to matching HTML elements. There you have it, the way to center text in HTML.