Flex items not respecting margins and box-sizing: border-box

前端 未结 2 1283
情深已故
情深已故 2020-11-28 15:51

I\'m trying to achieve a simple thing that we have in standard CSS.

Let\'s say that I have a grid system with 3 columns and box-sizing: border-box.

2条回答
  •  伪装坚强ぢ
    2020-11-28 16:37

    As well pointed out in Michael_B's answer margins are not taken into account when calculating flex item width. But you can subtract margins from flex-basis to get desired behaviour.

    For current case:

    header > span {
      /* 33.33% - margin-left - margin-right */
      flex: 1 1 calc(33.33% - 20px);
      margin: 10px;
    }
    

    Also you should set box-sizing: border-box to include padding (and borders) when calculating width.

    * {
      box-sizing: border-box;
    }
    
    .horizontal-layout {
      display: flex;
      width: 400px;
    }
    
    header > span { 
      flex: 1 0 calc(33.33% - 20px);
      margin: 10px;
    }
    
    header#with-border-padding {
      flex-wrap: wrap;
    }
    
    header#with-border-padding > span {
      flex: 1 0 calc(33% - 20px);
    }
    
    header#with-border-padding > .button {
      border: 1px solid black;
      padding-left: 5px;
    }
    
    header > .button {
      background-color: grey;
    }
    
    header > .app-name {
      background-color: orange;
    }
    NO flex-wrap: wrap, so it not respects the flex 33% 
    A B C D


    WITH flex-wrap: wrap : I expect to have 3 boxes in first row and D box in a down
    A B C D

提交回复
热议问题