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

后端 未结 3 1599
一整个雨季
一整个雨季 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:34

    Simply remove width:100% and you will better understand:

    section {
      background: lightgrey;
      width: 1000px;
    }
    
    div {
      background: red;
      display: flex;
    }
    
    form {
      background: blue;
      box-sizing: border-box;
    }
    
    input {
      box-sizing: border-box;
      margin: 0.3125em 0 0.625em;
    }
    One input field.
    Two input fields.
    Three input fields.
    Four input fields.

    The inputs are defining the width of the blue box and then this width will be the reference of the width: 100%; making all the input to be full width of it.


    Basically, a percentage value need a reference so the width of the blue box is first calculated considering the content and then the input will use that width as reference.

    This can also happen with simple inline-block elements

    section {
      background: lightgrey;
      width: 1000px;
    }
    
    div {
      background: red;
      display: inline-block;
    }
    
    form {
      background: blue;
      box-sizing: border-box;
    }
    
    input {
      box-sizing: border-box;
      width:100%;
      margin: 0.3125em 0 0.625em;
    }

    More details about percentage sizing here: https://www.w3.org/TR/css-sizing-3/#percentage-sizing

    You can find an explicit example of such behavior:

    For example, in the following markup:

    When calculating the width of the outer

    , the inner

    When using display: block, everything works as intended.

    Simply because the width calculation of block element is different and doesn't depend on the content unlike for inline-block elements or flex items where the content define the width

提交回复
热议问题