CSS Flexbox center horizontally and vertically a text example

CSS flex example to the horizontal and vertical center of child items and text in HTML example

Let’s declare a flex container and add child elements to the 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, the 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 by 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 vertical in flex container child items

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

justify-content: center: This displays the items to center 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 horizontal direction

flexbox direction column center alignment horizontally and vertically

Conclusion

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