EN
CSS - justify single flexbox item
0 points
In this article, we would like to show you how to justify a single flexbox item by "overriding" justify-content
property in CSS.
Quick solution:
xxxxxxxxxx
1
.container {
2
display: flex;
3
justify-content: flex-start;
4
}
5
6
.item1 {
7
/* ... */
8
}
9
10
.item2 {
11
/* ... */
12
}
13
14
.item3 {
15
margin-left: auto; /* <--- justifies last item to flex-end */
16
}
In this example, we justify the content inside the container
to flex-start
.
To "override" the justify-content
property we use a simple trick - set margin-left: auto;
for item3
so it will be justified to flex-end.
Runnable example:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
.container {
7
border-radius: 10px;
8
background: #3085d6;
9
height: 200px;
10
width: 200px;
11
box-shadow: 3px 3px 20px 0px grey;
12
display: flex; /* <----- required */
13
justify-content: flex-start; /* <----- justifies content to flex-start */
14
}
15
16
.item1 {
17
margin: 2px;
18
border: 1px solid #6e6e6e;
19
border-radius: 5px;
20
background: #ffc353;
21
height: 50px;
22
width: 50px;
23
text-align: center;
24
line-height: 50px;
25
}
26
27
.item2 {
28
margin: 2px;
29
border: 1px solid #787878;
30
border-radius: 5px;
31
background: #92ff53;
32
height: 50px;
33
width: 50px;
34
text-align: center;
35
line-height: 50px;
36
}
37
38
.item3 {
39
margin: 2px;
40
border: 1px solid #575757;
41
border-radius: 5px;
42
background: #dd53ff;
43
height: 50px;
44
width: 50px;
45
text-align: center;
46
line-height: 50px;
47
48
margin-left: auto; /* <--- "overrides" justifying to flex-start */
49
}
50
51
</style>
52
</head>
53
<body>
54
<div class="container">
55
<div class="item1">1</div>
56
<div class="item2">2</div>
57
<div class="item3">3</div>
58
</div>
59
</body>
60
</html>