Dacramash Dacramash - 3 months ago 15
CSS Question

Input field next to submit button (unknown widths + space)

I am trying to set my form so that it has an input field on the left with a submit button on the right. However, I need the input field to take all the remaining space minus a space of 1rem.

I have tried with this code:

<aside class="widget-area">
<section class="widget-search">
<form class="search-form">
<label class="search-label">
<span class="search-reader-text">Search for:</span>
<input type="search" class="search-field" placeholder="Search..." />
</label>
<input type="submit" class="search-submit" />
</form>
</section>
</aside>

.search-form {
display: table;
table-layout: fixed;
width: 100%;
}

.search-label {
display: table-cell;
}

.search-input {
display: table-cell;
}


However, all this does is move the button inside the input field...

I also tried this route:

.search-form {
display: table;
}

.search-label {
display: table-cell;
padding: 0 1rem 0 0;
}

.search-input {
display: table-cell;
}


Now the button is next to the input field, but it goes out of the container...

Answer

You can use Flexbox on a container so your input will be able to take any remaining space.

Codepen with 2 examples where buttons have different widths and still, input adapt to each situation automagically.

Relevant CSS is:

.form-line {
  display: flex;
}
.search-input {
  flex: 1 0 auto;
}

where the 3 components of flex means: "can grow, can't shrink, flex-basis set to auto" (somewhat related to a starting width here)

Compatibility: IE9+
Cheat sheet: CSS-tricks

Note: I added for/id on label/input so that all screen readers can associate them and read out the label to their users

Comments