{

CSS Flexbox center horizontally and vertically an text example


CSS flex example to the horizontally and vertically center of a child items and text in HTML example

Let’s declare a flex container and add child elements to display. Declared four child items inside a flex container.

<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
  <body>
<div  class="container">
  <div class="item">
   <p>One</p>
  </div>
  <div class="item">
   <p>Two</p>
  </div>
  <div class="item">
   <p>Three</p>
  </div>
  <div class="item">
   <p>Four</p>
  </div>
</div>
</body>
</html>

In CSS styles, container contains flex and flex-direction is column.

Child items inside a flex container added a gap with 20px.

flex items are aligned with left by default.

.container{
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.item{
  width: 100px;
  height: 100px;
  color: white;
  background-color:red;
  border: 1px solid green;
}

Render the page as

flexbox direction column center alignment

Let’s see the flex container with changing the flex-direction to row,

Rendered as follows

flexbox direction row center alignment

CSS flexbox align-center horizontally and vertically example

To align the horizontal and vertically in flex container child items

Add the justify-content: center and align-content: center; to flex container.

justify-content: center: This displays the items to center in vertically
align-content: center: This displays the items to center horizontally.

And update the child item text-align to center;

<!DOCTYPE html>
<html>
<head>
<title>HTML, CSS and JavaScript demo</title>
</head>
  <body>
<div  class="container">
  <div class="item">
   <p>One</p>
  </div>
  <div class="item">
   <p>Two</p>
  </div>
  <div class="item">
   <p>Three</p>
  </div>
  <div class="item">
   <p>Four</p>
  </div>
</div>
</body>
</html>

css

.container{
  display: flex;
  flex-direction: column;
  justify-content: center;  
  align-items: center;    
  gap: 20px;
  
}
.item{
  width: 80px;
  height: 80px;
  color: white;
    text-align: center;
  background-color:green;
  border: 1px solid green;
}

Render content as flexbox direction row center alignment horizontally and vertically

Change flex-direction to column to display flex items horizontally direction

flexbox direction column center alignment horizontally and vertically

Conclusion

Learned how to stye items center horizontally and vertically in flex container CSS.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.