Why does input field width grow with number of inputs (flexbox)?

后端 未结 3 1602
一整个雨季
一整个雨季 2021-01-22 02:41

I\'m implementing a form which has multiple sections with different numbers of input fields. When using display: flex on the parent div and 100% width on the input

3条回答
  •  旧巷少年郎
    2021-01-22 03:20

    With display: block on the main containers (div), the form element – the child of the div – automatically occupies 100% width of its parent.

    With display: flex on the main containers, the form element defaults to flex-basis: auto, which is the width of its content.

    So if you want the same behavior with display: flex, add flex: 1 0 0 (aka flex: 1) to the form elements. This tells them to take full width of their parents, like display: block.

    section {
      background: lightgrey;
      width: 1000px;
    }
    
    div {
      background: red;
      display: flex;
    }
    
    form {
      flex: 1;  /* flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
      background: blue;
      box-sizing: border-box;
    }
    
    input {
      box-sizing: border-box;
      width: 100%;
      margin: 0.3125em 0 0.625em;
    }
    One input field.
    Two input fields.
    Three input fields.
    Four input fields.

提交回复
热议问题