EN
CSS - center child element horizontally using flexbox (column direction)
0 points
In this article, we would like to show you how in CSS center an element horizontally using flexbox when elements are ordered in the column direction.
Quick solution:
xxxxxxxxxx
1
.container {
2
display: flex;
3
flex-direction: column;
4
align-items: center;
5
}
Screenshot:

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