Thanks to CSS, we have a wide variety of ways to center text within an HTML element, either by aligning it with the text-align property or by centering it within the HTML element using CSS properties like flexbox and grid.
1. Centering the title of an HTML element
For this example, we will use an <h1> tag as the title, which by default has the text aligned to the left. To center it, simply add the following property to our CSS code.
h1 {text-align: center;}
This code also applies to align the text of any HTML tag, such as p, div, or footer.
2. Centering text in a div horizontally
To center the text in a div horizontally, we will use CSS flexbox. For this example, we'll need to create a div and add some content to it.
<div><h2>This is the element we will center.</h2></div>
div {display: flex;justify-content: center;}
By adding the display: flex property, we turn the div into a flexible element, and with the justify-content: center property, we place the content in the center of the element.
3. Centering the content of an HTML element vertically
To center the text of an element vertically, instead of using the justify-content property, we will use the align-items: center property as in the following example:
<div><h2>Content of the element for this example.</h2></div>
div {min-height: 400px;display: flex;align-items: center;}
Bonus: Centering text in both axes
To have text centered in both directions, we will use the two CSS flexbox properties used earlier but apply both to the same element simultaneously.
<div><h2>Content of the element for this example.</h2></div>
div {min-height: 400px;display: flex;align-items: center;justify-content: center;}
Using the above CSS properties, you can also easily center an image with CSS. I hope this article has been helpful to you. Thank you very much for reading the entire post.
I am Juneiker Castillo, a passionate front-end web developer deeply in love with programming and creating fast, scalable, and modern websites—a JavaScript enthusiast and a React.js lover ⚛️.
About me