How to Right-align flex item?
CSS | flex-box
Flex-box is simply a web layout method that allows developers to align the elements easily and much more. The whole concept of flex-box depends on two major pillars: main-axis and cross-axis.

Representation of flex-box
To align the flex items left/right, We need to deal with the main-axis, which can be done using flex-box properties. A detailed explanation is given below:
Example 1: Right aligning flex item using flex-direction property
<!DOCTYPE html>
<html>
<head>
<title>Right Alignment</title>
<style>
#container
{
width:600px;
height: 300px;
border: 5px solid black;
display: flex;
flex-direction: row-reverse;
}
#container div
{
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<div id="container">
<div style="background-color:#389900;">one</div>
<div style="background-color:#08ebb2;">two</div>
<div style="background-color:#dd2289;">three</div>
<div style="background-color:#fcff66;">four</div>
</div>
</body>
</html>
|
When flex-direction is set as “row-reverse” it not only right aligns the flex items but reverses the order of the items also. In simple words, flex-items now expand from right to left as shown in the given figure.
Output:

Figure-1
Example 2: Right aligning flex item using justify-content property
<!DOCTYPE html>
<html>
<head>
<title>Right alignment</title>
<style>
#container
{
width:600px;
height: 300px;
border: 5px solid black;
display: flex;
justify-content: flex-end;
}
#container div
{
width: 100px;
height: 50px;
}
</style>
</head>
<body>
<div id="container">
<div style="background-color:#389900;">one</div>
<div style="background-color:#08ebb2;">two</div>
<div style="background-color:#dd2289;">three</div>
<div style="background-color:#fcff66;">four</div>
</div>
</body>
</html>
|
When justify-content is set to “flex-end”, it instantly shifts all the flex-items to the end of the flex-container along the main-axis, i.e flex items get right aligned. It is different from the above-used method in terms of direction only as in this, flex-items will expand from left to right only. It will be more clear with the given figure.
Output:

Figure-2
Last Updated :
01 Dec, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...