How to Vertically Center Text inside a div using CSS Flexbox?

Aligning elements horizontally and vertically has always been frustrating in HTML & CSS. We try all sorts of tricks and hacks which sometimes work but sometimes do not.

But after the introduction of CSS flexbox, things have become much easier and simpler than we think. CSS flexbox gives you full control to align HTML elements both horizontally as well as vertically.

To vertically center a text inside its containing div, you have to simply set the align-items property to center. In addition to that, if you want to center the text horizontally as well, you have to set the justify-content property to center.

The following example centers the text vertically as well as horizontally inside its containing div:


   display: flex;
   height: 300px;
   align-items: center;
   justify-content: center;
   border: 2px solid red;

Here is the summary:

  • align-items: Align flex items vertically
  • justify-content: Align flex items horizontally


  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts