Search code examples
htmlcssflexbox

How can I make this button stop taking up the whole width within a flex container?


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>

Current: enter image description here Desired: enter image description here

What I've Tried Now:

Main Parent Div:

enter image description here

Button Div:

enter image description here

Button text is now properly located to the right side but the left padding on the button still extends out all the way.


Solution

  • 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 the flex: 1; rule as that's explicitly telling the element to grow.

    For example:

    .parent {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }
    <div class="parent">
      <div class="left">Left</div>
      <div class="center">Center</div>
      <button class="right"></button>
    </div>