In this CSS article we want to learn How to Center Text in CSS, centering text on web page is common design requirement, but it can be tricky to achieve if you’re not familiar with CSS. in this article we want to cover some simple techniques to center text using CSS.
How to Center Text in CSS
Let’s talk about the first way and that is Using text-align property, simplest way to center text is to use the text-align property in CSS. this property is used to set the horizontal alignment of text within an element. this is an example:
1 2 3 |
.center { text-align: center; } |
In the above code we have created a class named center and set its text-align property to center. now any text within an HTML element with the class center will be centered.
Another way to center text is to use the margin property. this method works by setting equal margins on both the left and right sides of the element. this is an example:
1 2 3 |
.center { margin: 0 auto; } |
In the above code we have created a class named center and set its margin property to 0 auto. this will center the element horizontally within its parent container. Note that this method only works for block level elements. if you want to center inline elements like text within a paragraph, you need to wrap the text with block level element like <div>.
Flexbox is powerful layout tool in CSS that allows you to create flexible and responsive layouts. one of its benefits is that it makes centering elements easy. this is an example:
1 2 3 4 5 |
.container { display: flex; justify-content: center; align-items: center; } |
In the above code we have created a container with class container and set its display property to flex. this creates flex container. after that we have used justify-content and align-items properties to center the child element both horizontally and vertically within the container.
You can use the styles inside HTML.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<!DOCTYPE html> <html> <head> <title>Center Text Example</title> <style> .center { text-align: center; } </style> </head> <body> <h1 class="center">This text is centered</h1> <p>This is some other text that is not centered.</p> </body> </html> <!DOCTYPE html> <html> <head> <title>GeeksCoders.com</title> <style> .center { text-align: center; } </style> </head> <body> <h1 class="center">Welcome to geekscoders.com</h1> <p>How to Center Text in CSS</p> </body> </html> |
In the above code we have created simple HTML document with heading and paragraph element. heading element has a class of center and we have applied the CSS text-align property with a value of center to that class. this centers the text within the heading element.
This will be the result