129 views
How to vertically align text with CSS
To vertically align text with CSS, you can use the vertical-align
property. However, it’s essential to understand that the vertical-align
property primarily applies to inline and table-cell elements and their alignment with respect to other inline or table-cell elements.
Vertical alignment for block-level elements (like <div>
, <p>
, etc.) requires different techniques. Here are several methods for vertically aligning text in different scenarios:
- Vertical Align for Inline or Table-Cell Elements:
For inline or table-cell elements, you can use thevertical-align
property to control the vertical alignment of text relative to its surrounding content.
.inline-text {
vertical-align: middle;
}
/* Example HTML */
<span class="inline-text">This text will be vertically aligned.</span>
- Vertically Aligning Block-Level Elements with Flexbox:
To vertically align text within a container, you can use Flexbox.
.container {
display: flex;
align-items: center; /* Vertical alignment (center, flex-start, flex-end, etc.) */
/* justify-content: center; */ /* Horizontal alignment (center, flex-start, flex-end, etc.) */
height: 200px; /* Set container height to vertically center text */
}
/* Example HTML */
<div class="container">
<p>This text will be vertically aligned using Flexbox.</p>
</div>
- Vertically Aligning Block-Level Elements with CSS Grid:
Another approach is to use CSS Grid for vertical alignment.
.container {
display: grid;
place-items: center; /* Vertically and horizontally center the content */
height: 200px; /* Set container height to vertically center text */
}
/* Example HTML */
<div class="container">
<p>This text will be vertically aligned using CSS Grid.</p>
</div>
- Vertically Centering a Single Line of Text with Line-Height:
For single-line text, you can use theline-height
property to vertically center it within its container. Set theline-height
to be equal to the container’s height.
.container {
height: 50px; /* Set container height */
line-height: 50px; /* Vertically center the single line of text */
}
/* Example HTML */
<div class="container">This text will be vertically aligned using line-height.</div>
These are some common methods for vertically aligning text in CSS. The approach you choose depends on the context and layout of your web page. For multiline text, you may need to combine techniques or use additional CSS properties to achieve the desired vertical alignment.