EN
CSS - center child element vertically using flexbox (row direction)
3 points
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:
xxxxxxxxxx
1
.container {
2
display: flex;
3
align-items: center;
4
}
Screenshot:

In this example, we're using a flexbox with the align-items
property to vertically center the item inside the flex container.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.container {
7
border-radius: 10px;
8
background: #3085d6;
9
width: 200px;
10
height: 200px;
11
box-shadow: 5px 5px 15px gray;
12
13
display: flex; /* <----- required */
14
align-items: center; /* <----- required */
15
}
16
17
.item {
18
border: 1px solid black;
19
border-radius: 5px;
20
background: #ffc353;
21
width: 50px;
22
height: 50px;
23
}
24
25
</style>
26
</head>
27
<body>
28
<div class="container">
29
<div class="item"></div>
30
</div>
31
</body>
32
</html>
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.container {
7
border-radius: 10px;
8
background: #3085d6;
9
width: 200px;
10
height: 200px;
11
box-shadow: 5px 5px 15px gray;
12
13
display: flex; /* <----- required */
14
align-items: center; /* <----- required */
15
}
16
17
.item {
18
margin: 2px;
19
border: 1px solid black;
20
border-radius: 5px;
21
background: #ffc353;
22
width: 50px;
23
height: 50px;
24
}
25
26
</style>
27
</head>
28
<body>
29
<div class="container">
30
<div class="item"></div>
31
<div class="item"></div>
32
<div class="item"></div>
33
<div class="item"></div>
34
</div>
35
</body>
36
</html>