I have a flex container with flex direction set to row with 3 items. I need all 3 items in a single row, with the first and last items to the far left and right side respectively, and the middle 2nd item to be centered. The problem I am getting is the button (3rd item) is stretching super wide and filling the entire width in its respective space. Any help hugely appreciated here.
.parent {
display: flex;
flex-direction: row;
}
.left, .right {
flex: 1;
}
<div class="parent">
<div class="left">Left</div>
<div class="center">Center</div>
<button class="right"></div>
</div>
What I’ve Tried Now:
Main Parent Div:
Button Div:
Button text is now properly located to the right side but the left padding on the button still extends out all the way.
4
Answers
You can wrap the
<button>
in a<div class="right">
and usejustify-content: end
on that:…or use
display: grid
and setjustify-self: end
for.right
:For starters, your markup is invalid.
<button>
should be lowercase and should have a closing</button>
, not a closing</div>
. Once you correct that…You can control the spacing of elements with
justify-content
. Also, get rid of theflex: 1;
rule as that’s explicitly telling the element to grow.For example:
Put the button inside of
<div class="right">
You are setting
flex: 1
on the two side items. Specified like that, it setsflex-grow: 1
andflex-basis: 0
: you are telling the two side items to grow, and not the center one.You can either make none grow and distribute the items evenly, or make the center one grow and not the side ones.
Distribute:
Grow:
Also, your button markup is invalid: you are closing it with a
</div>
tag.