How to add 1px margin to a flex item that is flex: 0 0 25%?

后端 未结 3 1414
挽巷
挽巷 2020-11-27 08:39

I am testing few different layouts with flexbox and I have the following problem.

I have a image gallery with flex items set up flex:0 0 25%; and I woul

3条回答
  •  借酒劲吻你
    2020-11-27 09:24

    You can use flex: 1 0 22% for example. This will allow your element to be defined by 22% as flex-basis (so only 4 elements per row) and they will grow to fill the remaining space left by margin (since flex-grow is set to 1)

    #foto-container {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      margin: 10px;
    }
    
    .foto {
      flex: 1 0 22%;
      min-height: 50px;
      margin: 1px;
      background-color: red;
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    1
    2
    3

    The value of flex-basis should be bigger than (20% - margin * 2) and lower than (25% - margin * 2). The first value will allow you to have 5 elements per row, so having a bigger value will make them 4 and having a bigger value than the second one will make the number of element to be 3 per row.

    #foto-container {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-around;
      margin: 10px;
    }
    
    .foto {
      flex: 1 0 21%;
      min-height: 50px;
      margin: 1px;
      background-color: red;
      animation: change 4s linear infinite alternate; 
    }
    
    @keyframes change {
      0%,40% {flex: 1 0 calc(20% - 2 * 1px);background:yellow;}
      41%,59% {background:red;}
      60%,100% {flex: 1 0 calc(25% - 2 * 1px + 1px);background:green;}
    }
    1
    2
    3
    4
    5
    6
    7
    8
    9
    1
    2
    3

提交回复
热议问题