
p {
text-align: center;
}
div {
text-align: center;
}
.container {
text-align: center;
}
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod eempor incididunt ut.
Do you want to align the text vertically centered? See vertically center text.
An efficient way to write CSS for centering text
To maximize productivity, you have to write less code and do more.
At the top of your CSS file, choose a class name whatever you like, and write the CSS to center the text. For example-
.t-center {text-align: center;}
/* write this on your CSS file once */
/* and use this class name (.t-center) on your HTML as much time you need. */
/* And you can follow this same process for other elements */
/* such as image, iframe, etc */
.i-center {max-width: 900px; display: block; margin: 0 auto;}
/* for centering images */
By doing this once, you can apply this class name as many times on your HTML. For example-
<section>
<h2>This is a heading</h2>
<p class="t-center">This is a paragraph.</p>
<img class="i-center" src="image.jpg" alt="photo">
<p>This is also a paragraph that is not centered.</p>
</section>
Centering text in a given width
Imagine a situation where you have to center align a paragraph that has to be 300 pixels in width.
Distinctio amet saepe illum illo placeat voluptatibus facilis eveniet ea? Similique rem recusandae ut quam minus, blanditiis beatae delectus itaque quaerat odio.
p {
width: 300px;
margin: 0 auto;
text-align: center;
}
/* If you do not assign the margin: 0 auto; the text will be centered itself
but it (white box) will stay on the left side of the div/container. */
The paragraph or p-tag is already a block-level element by born, so you don’t have to assign “display: block.”