OneBite.Dev - Coding blog in a bite size

vertically align text css

Code snippet for how to vertically align text css with sample and detail explanation

Vertical alignment of text is a feature in CSS that’s used to set the position of the text within its parent element along the vertical axis. With this feature, you can position your text top, bottom, middle, or use any other custom alignment. This article covers how to use CSS to vertically align text.

Code Snippet: Vertical Alignment in CSS

The following code snippet demonstrates how to vertically align text using the CSS vertical-align property:

.parent {
  height: 200px;
  line-height: 200px;
}

.child {
  display: inline-block;
  vertical-align: middle;
  line-height: normal;
}

And in your HTML:

<div class="parent">
  <div class="child">
    Vertically centered text
  </div>
</div>

Code Explanation for Vertical Alignment in CSS

To begin with, in the CSS, we are defining a parent class that will contain our text. This class has a height of 200px, and a line-height equal to the height. By default, the line-height property sets the height of a line box. For a single line box, this defines the height that the contents of the box should be centered within.

Next, we have the child class, which works with the text we want to align vertically. The display property is set to inline-block. This means that the text should flow along with any adjacent elements, but also respect padding and margins like a block element.

The vertical-align property is set to middle. This instructs the browser to arrange the text so that it’s vertically aligned in the middle of the parent container. If the parent container has a height greater than the text, the text will appear centered within the vertical space.

Lastly, line-height is set to normal. This resets the abnormal line-height specified in the parent, so the text within the child div will have a natural line-height.

In the HTML section, we wrap our text in two div elements with classes of “parent” and “child” respectively. The text is placed inside the child div, which is nested inside the parent div, thus the text inherits the CSS properties defined for these classes giving us a vertically aligned text.

css