How to Make the Middle Item Stay Centered?



Centering the middle item in a layout while ensuring it doesn't move if other items are removed is a common design challenge, this article explores ways to center the middle item using CSS techniques that maintain its position even if adjacent elements are absent.

Using Flexbox with Absolute Centering

Flexbox offers a straightforward way to center an item within a container. By setting the middle item to have margin property set to auto, it remains centered without depending on adjacent items.

Example Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Center Middle Item with Flexbox</title>
    <style>
        .container {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #f3f3f3;
            padding: 20px;
        }
        .item {
            padding: 10px 20px;
            background-color: #007bff;
            color: white;
            border-radius: 5px;
        }
        .middle-item {
            margin: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="item">Left</div>
        <div class="item middle-item">Center</div>
        <div class="item">Right</div>
    </div>
</body>
</html>

Output

Make the Middle Item Stay Centered

Updated on: 2024-11-14T09:47:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements