skip to Main Content

Hey guys can you look at following code and explain me why flexbox is behaving in this manner.

1.

<!DOCTYPE html>
<html>
<head>
    <style>
        body{
            position: relative;
        }
        .container {
            display: flex;
            justify-content: space-between;
        }
    </style>
</head>
<body>

<div class="container">
    <div class="item"> hello</div>
    <div class="item"> hi</div>
</div>

</body>
</html>
.container {
            position: absolute;
            left: 0;
            top: 0;
            display: flex;
            justify-content: space-between;
        }
.container {
            position: absolute;
            left: 0;
            right:0;
            top: 0;
            display: flex;
            justify-content: space-between;
        }

I was expecting that flex-box would automatically take full width given justify-content: space-between; Normally it works but when I make position of the container it doesn’t take full width and I have to force it.

2

Answers


  1. The problem with your code is that the position: absolute property removes the element from the usual document flow, causing the.container element to no longer take up the full width of its parent container. When an element is removed from the usual flow, it no longer interacts with other elements in the same way.

    To resolve this issue, add the left: 0 and right: 0 properties to.container to force it to take up the entire width of its parent container. As a result, the justify-content: space-between property will function as planned.

            body{
                position: relative;
            }
            .container {
                position: absolute;
                left: 0;
                right: 0;
                top: 0;
                display: flex;
                justify-content: space-between;
            }
    <!DOCTYPE html>
    <html>
    <head>
    
    </head>
    <body>
    
    <div class="container">
        <div class="item"> hello</div>
        <div class="item"> hi</div>
    </div>
    
    </body>
    </html>
    Login or Signup to reply.
  2. When you have a div, it takes the full width, so the justify-content works but when you add position absolute, it takes the width of its content.

    So you need to specify the width as you did, then the justify content will take full width:

    .container {
                position: absolute;
                left: 0;
                right:0;
                top: 0;
                display: flex;
                justify-content: space-between;
            }
    

    or just give it :

    .container {
                position: absolute;
                left: 0;
                width: 100%;
                display: flex;
                justify-content: space-between;
            }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search