How To Center Text In Html Css

In this tutorial, we will learn how to center text in HTML using CSS. Centering text might sound simple, but it can be a bit tricky depending on the type of elements you’re working with. We will explore various methods to achieve this, including using the text-align and margin properties in CSS.

Step 1: Create your HTML structure

Create a basic HTML document structure with a <head> and a <body> section. Inside the <body> section, insert a <div> element with an id attribute set to “centered_text”. Add any text content you would like to center within this div.

Step 2: Add internal or external CSS

You can either add internal CSS within a <style> tag inside the <head> section of your HTML document, or you can link to an external CSS file.

To add internal CSS, insert the following <style> element inside your <head>:

To link to an external CSS file, create a new file with a “.css” extension, and insert a <link> element inside the <head>, as shown below:

For this tutorial, we will use internal CSS.

Step 3: Using text-align to center text

Add the following CSS rule inside the <style> tag to center the text within the “centered_text” div using the text-align property:

This method works well for inline and inline-block elements, but might not work as expected for block-level elements such as divs or paragraphs.

Step 4: Center a block element using the margin

If you want to center a block element entirely, you can use the margin property to adjust its position within its parent container.

Here’s an example:

In the example above, the “centered_text” div is set to become an inline-block element, and the left and right margins are set to “auto”. This allows the browser to automatically calculate the equal amount of margin on both sides, thereby centering the element within its parent container.

Step 5: Consider browser compatibility

Keep in mind that some older browsers, such as Internet Explorer 8 and below, might not support the above CSS rules for centering elements. Make sure to test your website on various browsers and devices to ensure your content is being displayed as intended.

Full Code


In this tutorial, we’ve learned how to center text in HTML using CSS. Understanding both the text-align and margin properties are essential when designing and laying out your web pages. Remember to always test your website on multiple browsers and devices to ensure you’re providing a consistent user experience across all platforms.