Trusted answers to developer questions

How to center align text using CSS

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

svg viewer

Often, while deciding how to structure the web page’s data, there is a need to align the text accordingly. You can align text to the left, right, or center according to the desired design. In this article, we will see how to format and center align the text using CSS.

Using text-align

Take a look at the code below:

In the code above, we have defined a style class named center. This class has a single attribute called text-align that can take either of the following four inputs: center, left. right, and justify. For the sake of this article, we assigned center to text-align. To observe how it works, click on the run button and see the difference between left align (default) and center align.

Using Padding

Take a look at the code below:

It’s a bit tedious to align your text by eyeballing the margin and setting the padding value, but it gives you more freedom in the way you want to style it. As in the previous example, we have a class named center. This class only has one attribute called padding. Padding is the numeric value in pixels that conveys how much space you want to append to the left and top of the text. Since we wish to center align text horizontally, we can leave the first argument as 00px and set 200px as the second argument. To observe how it works, click on the run button and look the difference between left align (default) and center align.

RELATED TAGS

html
css

CONTRIBUTOR

Shahpar Khan
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?