Languages
[Edit]
EN

CSS - center child element vertically using flexbox (row direction)

3 points
Created by:
Violetd
865

In this article, we would like to show you how in CSS, center an element vertically using flexbox when elements are ordered in the row direction (by default flex uses flex-direction: row; so it is not needed to add it).

Quick solution:

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

Screenshot:

Center content element vertically using flexbox in row direction - CSS
Center content element vertically using flexbox in row direction - CSS

 

Practical example

In this example, we're using a flexbox with the align-items property to vertically center the item inside the flex container.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .container {
        border-radius: 10px;
        background: #3085d6;
        width: 200px;
        height: 200px;
        box-shadow: 5px 5px 15px gray;
      
        display: flex;        /*  <----- required   */
        align-items: center;  /*  <----- required   */
    }

    .item {
        border: 1px solid black;
        border-radius: 5px;
        background: #ffc353;
        width: 50px;
        height: 50px;
    }

  </style>
</head>
<body>
  <div class="container">
    <div class="item"></div>
  </div>
</body>
</html>

Multiple items

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    .container {
        border-radius: 10px;
        background: #3085d6;
        width: 200px;
        height: 200px;
        box-shadow: 5px 5px 15px gray;
      
        display: flex;        /*  <----- required   */
        align-items: center;  /*  <----- required   */
    }

    .item {
        margin: 2px;
        border: 1px solid black;
        border-radius: 5px;
        background: #ffc353;
        width: 50px;
        height: 50px;
    }

  </style>
</head>
<body>
  <div class="container">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</body>
</html>

See also

  1. CSS - center child element vertically using flexbox (column direction) 

Alternative titles

  1. CSS - center content element vertically using flexbox (row direction)
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

CSS - Flexbox

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join