Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input doesn't respect flex container width

Tags:

css

flexbox

I have an input in a flex container in Chrome and it does not respect the width of the container unless I add a min-width: 0. This seems to work properly in IE.

What is going on here?

.input-with-button {
  display: flex;
  width: 100px;
  border: 5px solid blue;
  margin-bottom: 10px;
}

.input-with-button input {
  flex-basis: 100%;
}
<div class='input-with-button'>
  <div>Test</div>
</div>

<div class='input-with-button'>
  <input>
</div>
like image 246
sliptype Avatar asked Feb 13 '18 22:02

sliptype


1 Answers

The reason it works in IE is because it picks up the flex-basis: 100%, but it shouldn't.

The reason it overflows in Chrome (and should in IE), is that a flex item can't by default be smaller than its content since its min-width is set to auto, and in this case form elements, such as input, have a default width set using the browsers built it style sheet.

The reason min-width: 0 works, is when set to 0 the flex item will, since its flex-shrink value is 1 (the default), be allowed to shrink, and does to adjust to its parent's width.

Stack snippet

.input-with-button {
  display: flex;
  width: 100px;
  border: 5px solid blue;
  margin-bottom: 10px;
}

.input-with-button input {
  flex-basis: 100%;
  min-width: 0;                        /*  added  */
}
<div class='input-with-button'>
  <div>Test</div>
</div>

<div class='input-with-button'>
  <input>
</div>

As a side note, and as been mentioned in other answer(s), changing the default width of the element would of course also be an option, whether it is a form element or not.

Stack snippet

.input-with-button {
  display: flex;
  width: 100px;
  border: 5px solid blue;
  margin-bottom: 10px;
}

.input-with-button input {
  /*flex-basis: 100%;                     removed  */
  width: 100%;                        /*  added  */
}
<div class='input-with-button'>
  <div>Test</div>
</div>

<div class='input-with-button'>
  <input>
</div>
like image 98
Asons Avatar answered Dec 09 '22 04:12

Asons