Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always position button at the bottom of a form using flexbox

Tags:

html

css

I've created a Fiddle here: http://jsfiddle.net/gonw4udf/1/

I have a form that we want to be of a minimum height. Sometimes, the form only has very few fields which means that the "Submit" button immediately follows the last field. However, we want the "Submit" button to always be positioned at the bottom of its container.

I'm wondering if there is a way to do so without having to rely on position: absolute.

To clarify: If the form is taller than the minimum height, it's okay to put the "Submit" button immediately after its last field. However, for forms that are shorter than the minimum height, we always want the "Submit" button at the bottom of the form. There may be multiple valid heights for these form so a solution that doesn't rely on hard coding a pixel value would be best.

.form-wrapper {
  max-width: 300px;
  width: 300px;
  background-color: #D2B4DE;
  padding: 20px 30px;
  min-height: 300px;
}

.form {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  margin: 0 auto;
}

.form-title {
  font-weight: bold;
  font-size: 28px;
  margin-bottom: 8px;
}

.button {
  margin-top: 10px;
  justify-content: flex-end;
  align-items: baseline;
}
<div class="form-wrapper">
  <form class="form">
    <div class="form-title">
      This is a form title.
    </div>
    <label for="field">Field</label>
    <input type="text" id="field" placeholder="Enter a field" />

    <button class="button">Submit</button>
  </form>
</div>
like image 456
noblerare Avatar asked Nov 23 '25 20:11

noblerare


1 Answers

Here is the solution with justify-content: space-between. To make this work I've added 1 div wrapping the form content and another div wrapping the button.

.form-wrapper {
  max-width: 300px;
  width: 300px;
  background-color: #D2B4DE;
  padding: 20px 30px;
  min-height: 300px;
  display: flex;
}

.form {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  margin: 0 auto;
  flex: 1;
  justify-content: space-between;
}

.form-content {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.form-action {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}

.form-title {
  font-weight: bold;
  font-size: 28px;
  margin-bottom: 8px;
}

.button {
  margin-top: 10px;
  justify-content: flex-end;
  align-items: baseline;
}
<div class="form-wrapper">
  <form class="form">
    <div class="form-content">
      <div class="form-title">
        This is a form title.
      </div>
      <label for="field">Field</label>
      <input type="text" id="field" placeholder="Enter a field" />
    </div>
    <div class="form-action">
      <button class="button">Submit</button>
    </div>
  </form>
</div>
like image 187
Nik Avatar answered Nov 26 '25 11:11

Nik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!