Equal width using flex and border-box

前端 未结 5 1383
悲&欢浪女
悲&欢浪女 2020-12-21 01:35

I am using box-sizing: border-box; with varying border thicknesses within a flexbox. I want the elements within the flexbox to have equal widths, b

5条回答
  •  無奈伤痛
    2020-12-21 01:42

    The flex-grow property does not set the width or height of flex items. It's job is to distribute free space in the container among flex items.

    You have all items set to flex: 1, which is shorthand for:

    • flex-grow: 1
    • flex-shrink: 1
    • flex-basis: 0

    This distributes free space in the row equally among items.

    BUT borders (and padding) are factored in separately.

    flex-grow doesn't care about box-sizing: border-box, because box-sizing applies to width and height calculations which, as mentioned earlier, are not functions of flex-grow.

    Instead, use the flex-basis property, which is equivalent to width (in a row-direction container) and will respect box-sizing:

    flex: 0 0 20%;
    

    .container {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: 100px;
    }
    
    .container .block {
      height: 28px;
      flex: 0 0 20%; /* adjustment */
      border: 1px solid black;
      box-sizing: border-box;
    }
    
    .container .block.selected {
      border: 3px solid blue;
    }
    0 1 2 3 4

提交回复
热议问题