Home  »  Code Snippets   »   css vertical align with flexbox

How to vertically align text inside a flexbox?

Use flexbox to vertically align some content inside a div. This depends on the way we’re using the flex-direction. Most of the time it’s a combination of two properties but only one property can make your content aligned in the center vertically.

Add HTML Code

Add a div to contain sample text.

<!DOCTYPE html>
<html lang="en">
<body>
    <div>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Mollitia, ad? Perspiciatis recusandae excepturi eveniet ducimus culpa quas blanditiis labore in est itaque provident, voluptates deleniti autem dignissimos, id quis fugit.</div>
</body>
</html>

Add CSS

We're setting height of HTML,BODY to 100% so we can have text centered vertically.

html,body{height:100%; margin:0;padding:0;}
div {
  display: flex;
  align-items:center;
  width: 100%;
  height: 100%;
  font-size:4vw;
}

Edit Example

Please note in this example, We are using the Simple flex property.

The child element of the flex-box will be aligned in a row by default.

However, There can be another case with flex-directon:columnWhich will align items vertically. In this case, we have to use justify-content to align it vertically centered.

html,body{height:100%; margin:0;padding:0;}
div {
  display: flex;
  flex-direction:column;
  justify-content:center;
  width: 100%;
  height: 100%;
  font-size:4vw;
}

Similar Tags:

+ more tags