Flexbox provides all kind neat solution to complex scenarios. We will use some properties of CSS Flexbox to properly align the orphan flex item.
Imagine you have the html form with two buttons. One is called submit and other one is called reset. The reset button resets the form to its initial state. These buttons are displayed on online by default. In order to display them on each end of the container, we just need to set it’s parent display to flex.
<div class="container">
<button>Reset</button>
<button>Submit</button>
</div>
.container {
max-width: 400px;
display: flex;
justify-content: space-between;
}
With bit of CSS we get following results. space-between sets them far apart. Refer to this guide to find more about flexbox
Flexbox Challenge
Now the challenge is if that the submit button should always appear on right side. Because when the form is empty we don’t want to show the reset button
. As soon as I remove the reset button it snaps back to the left position according to normal document. This is due to space-between property of flexbox.
Solution
In order to achieve our desired result we need to add another element. Let’s call it spacer.
<div class="container">
<button>Reset</button>
<div class="spacer"></div>
<button>Submit</button>
</div>
The only css we add is flex-grow:1
.spacer {
flex-grow: 1;
}
There output is still the same but now if we comment the reset button we see our desired result
<div class="wrapper">
<!-- <button id="reset">Reset</button> -->
<div class="spacer"></div>
<button>Submit</button>
</div>
The signup button
is always appears on the right. That’s because the spacer with takes all the unallocated space, thanks to the flex-grow:1
property.