How To Vertically Center Text Css

Centering text vertically can be a bit tricky in CSS, especially when dealing with different screen sizes and dynamic content. However, there are several methods available to achieve this task. In this blog post, we will explore four different techniques to vertically center text using CSS:

  • Flexbox
  • Grid
  • Line-height
  • Transform

1. Flexbox

Flexbox is a powerful, modern layout module in CSS that allows you to create complex layouts with ease. To vertically center text using Flexbox, simply apply the following CSS rules to the container element:

    .container {
        display: flex;
        justify-content: center;
        align-items: center;
    }
    

This will center the text both horizontally and vertically within the container. You can see it in action by adding some text inside a <div> with the .container class:

    <div class="container">
        Vertically centered text
    </div>
    

2. Grid

CSS Grid Layout is another modern layout system, which can also be used to center text vertically. To achieve this, apply the following CSS rules to the container element:

    .container {
        display: grid;
        place-items: center;
    }
    

Just like with Flexbox, this will center the text both horizontally and vertically within the container. You can use it in a similar way:

    <div class="container">
        Vertically centered text
    </div>
    

3. Line-height

If you have a single line of text, you can also center it vertically using the line-height property. To do this, set the line-height equal to the container’s height:

    .container {
        height: 100px;
    }

    .centered-text {
        line-height: 100px;
    }
    

However, keep in mind that this method only works well for single lines of text. It may not work as intended for multiline text or if the container’s height is not fixed. To use this method, simply add the .centered-text class to your text element:

    <div class="container">
        <p class="centered-text">Vertically centered text</p>
    </div>
    

4. Transform

Another way to center text vertically is by using the CSS transform property. You can apply a translateY transformation to achieve this:

    .container {
        position: relative;
    }

    .centered-text {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }
    

This method can handle multiline text but requires the container to have a relative or absolute position. To use this method, add the .centered-text class to your text element:

    <div class="container">
        <p class="centered-text">Vertically centered text</p>
    </div>
    

Conclusion

In this blog post, we’ve explored four different techniques for vertically centering text in CSS: Flexbox, Grid, Line-height, and Transform. Depending on your specific use case and layout requirements, one of these methods should help you align your text vertically with ease.