How to Create LEFT-RIGHT Alignment of Containers with CSS Flex?

With CSS flexbox, you can easily create left-right alignment of containers. The flexible items are displayed horizontally using the flex-direction property, and the justify-content property controls how items are distributed along the main axis.

Syntax

.container {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

Method 1: Using Flex Direction

The div container is set to flex using the display: flex property. The flex-direction: row allows flex items to display horizontally, while justify-content: space-between pushes items to opposite ends −

Example

<!DOCTYPE html>
<html>
<head>
    <style> 
        #container {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            margin: 20px;
            padding: 20px;
            background-color: #f0f0f0;
            border: 2px solid #333;
        }
        .item {
            padding: 15px 30px;
            background-color: #4CAF50;
            color: white;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div id="container">
        <div class="item">Left Item</div>
        <div class="item">Right Item</div>   
    </div>
</body>
</html>
Two green boxes appear: one aligned to the left side and one to the right side of the container, with maximum space between them.

Method 2: Using Flex with Multiple Items

When you have multiple items and want some aligned left and others right, you can use margin-left: auto on the item you want to push to the right −

Example

<!DOCTYPE html>
<html>
<head>
    <style> 
        .navbar {
            display: flex;
            padding: 15px;
            background-color: #333;
            color: white;
        }
        .left-items {
            display: flex;
            gap: 20px;
        }
        .right-items {
            display: flex;
            gap: 20px;
            margin-left: auto;
        }
        .nav-item {
            padding: 8px 16px;
            background-color: #666;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <nav class="navbar">
        <div class="left-items">
            <div class="nav-item">Home</div>
            <div class="nav-item">About</div>
        </div>
        <div class="right-items">
            <div class="nav-item">Login</div>
            <div class="nav-item">Signup</div>
        </div>
    </nav>
</body>
</html>
A dark navigation bar appears with "Home" and "About" items aligned to the left, and "Login" and "Signup" items aligned to the right.

Conclusion

CSS flexbox provides powerful tools for left-right alignment. Use justify-content: space-between for two items, or margin-left: auto to push specific items to the right side of the container.

Updated on: 2026-03-15T15:21:50+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements