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
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
andright: 0
properties to.container to force it to take up the entire width of its parent container. As a result, thejustify-content: space-between
property will function as planned.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:
or just give it :