1

I am trying to put 5 inputs on one line. Simple, I thought. I have a parent div which has some margin on the left and right. I've put inputs with 20% width inside (5 x 20 = 100%). But the last input goes to the bottom, without a reason? Does someone knows why and how to solve this?

<body style="background: orange;">
  <div style="margin-left:10px; margin-right:10px;"> 
    <form>
      <input style="width: 20%; padding:0; margin:0;" type="text">
      <input style="width: 20%; padding:0; margin:0;" type="text">
      <input style="width: 20%; padding:0; margin:0;" type="text">
      <input style="width: 20%; padding:0; margin:0;" type="text">
      <input style="width: 20%; padding:0; margin:0;" type="text">
    </form>
  </div>
</body>
Stickers
  • 75,527
  • 23
  • 147
  • 186
Banjer_HD
  • 190
  • 2
  • 12

1 Answers1

2

I suggest to do it with flexbox.

form {
  display: flex;
}

input {
  flex: 1;
  min-width: 0;
}
<form>
  <input type="text">
  <input type="text">
  <input type="text">
  <input type="text">
  <input type="text">
</form>

Why your example didn't work is because:

  • <input> is inline level, it also has default padding and borders set from browser default stylesheet.

  • There is also white space in between the input boxes, they will be rendered as well.

To fix it with your original approach, you can do:

form {
  font-size: 0; /* remove white space */
}

input {
  font-size: 16px; /* reset font size */
  width: 20%;
  box-sizing: border-box; /* make border and padding part of width and height */
}
<form>
  <input type="text">
  <input type="text">
  <input type="text">
  <input type="text">
  <input type="text">
</form>

You can also float the input boxes so white space won't get rendered.

form:after { /* clear floats */
  content: "";
  display: table;
  clear: both;
}

input {
  float: left;
  width: 20%;
  box-sizing: border-box;
}
<form>
  <input type="text">
  <input type="text">
  <input type="text">
  <input type="text">
  <input type="text">
</form>
Stickers
  • 75,527
  • 23
  • 147
  • 186
  • 1
    While this is the best answer for how to do it in the modern web, it would probably be useful to the asker if you also explained why his way doesn't work. (Eg. because logically it *seems* like 5x20%=100% but it's really not.) – Roddy of the Frozen Peas Mar 13 '18 at 19:28
  • i agree with Roddy ;) as i guess this will be a bit complicated for him since he are not able to see easy stuffs like border/ white-space – Temani Afif Mar 13 '18 at 19:30
  • `it also has default padding` --> and especially border because he already removed the padding – Temani Afif Mar 13 '18 at 19:32
  • Thanks! My question is solved by this! You solved me a headache :) – Banjer_HD Mar 13 '18 at 19:32
  • 1
    OK guys, it is updated now, just need a little time to write it. – Stickers Mar 13 '18 at 19:38