John Smith John Smith - 2 months ago 9
CSS Question

100% width container with 8 same size inputs

I have a 100% width container that I would like to fill with 8 inputs of the same size. 100 / 8 = 12.5

The html:

<div id="container">
<input class="form" />
<input class="form" />
....
</div>


My css:

#container{
width: 100%;
background-color:red;
margin:0;
}

.form{
width:12.5%;
margin:0;
}


As you can see in this fiddle: https://jsfiddle.net/7z7e63cb/

The last input is displayed in another line. Why? and how can I fix it? Thanks

Answer

In my opinion, the best way to do this in 2016 is to use Flexbox: see updated fiddle.

The main trick is done with the following lines:

#container{
  ...
  display: flex; /* turns the Flexbox magic on! */
}

.form{
  flex: 1; /* makes the elements equal width, no extra calculation needed */
  min-width: 0; /* allows them to shrink below their default width */
  ...
}

html,
body {
  margin: 0;
  padding: 0;
}
#container {
  width: 100%;
  background-color: red;
  margin: 0;
  display: flex; /* turns the Flexbox magic on! */
}
.form {
  flex: 1; /* makes the elements equal width, no extra calculation needed */
  min-width: 0; /* allows them to shrink below their default width */
}
<div id="container">
  <input class="form" />
  <input class="form" />
  <input class="form" />
  <input class="form" />
  <input class="form" />
  <input class="form" />
  <input class="form" />
  <input class="form" />
</div>

Comments