Equal width using flex and border-box

前端 未结 5 1391
悲&欢浪女
悲&欢浪女 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 box-sizing: border-box is used to change the default CSS box model used to calculate width and height of the elements.

    So would be like this:

    • total width = border + padding + content width

      and

    • total height = border + padding + content height

    But that doesn't happen in flex-grow, but in flex-basis

    Here is a good tutorial about flexbox


    So you can use flex:0 20% instead of flex:1,

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

    Note: if you have more elements than 5, then you can use calc() like this flex: 0 calc(100%/8) where 8 is the # of elements you will have

    Snippet with more elements

    .container {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: 100px;
    }
    
    .container .block {
      height: 28px;
      flex: 0 calc(100%/8);
      border: 1px solid black;
      box-sizing: border-box;
    }
    
    .container .block.selected {
      border: 3px solid blue;
    }
    0 1 2 3 4 5 6 7

提交回复
热议问题