CSS HTML

How to align text vertically with CSS

February 18, 2022

How to align text vertically with CSS

In this article we will learn the easiest way to align text vertically in your HTML project, using only CSS quickly.

text vertically with CSS cover

What’s up programmer, how are you? Let’s  learn something new

Aligning texts horizontally is pretty easy, we just need to add the text-align rule with center

But what about vertically? The text-align rule doesn’t work the same

So let’s see an example to see in practice how to do this alignment:

<div id="container">
 <p id="text">Some text here</p>
</div>

Here we have our div with container id, which contains the text to be centered

And the text is in a <p> tag, which is a very common practice

Now let’s go to the CSS to center vertically:

body {
 margin: 30px;
}

#container {
 width: 500px;
 height: 500px;
 border: 1px solid red;
}

#text {
 position: relative;
 text-align: center;
 line-height: 500px;
}

With this code we can align the text in the center, check out the result:

Let’s explain the code, first we settle a margin in the body, just to detach the ends of the <div> from the browser, it is not necessary

Then we dimension the container, which will probably happen in your case too, it has a height and width

Then the magic is in the #text, we insert relative position, to follow the parent and a line height (line-height) equal to the height of the parent, this makes it centered

And also the text-align with center, as said before to align horizontally

Conclusion

We learned how to align text vertically in this article, we just need to scale the parent container

Let’s now determine a height, so that in the child element (the text), we insert a line-height equal to the dimensioned height of the parent

This way we will have the text centered vertically 😀

Want to learn more about CSS? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x