How to set a fixed width column with CSS flexbox

后端 未结 2 1651
春和景丽
春和景丽 2020-12-12 10:33

CodePen: http://codepen.io/anon/pen/RPNpaP.

I want the red box to be only 25 em wide when it\'s in the side-by-side view - I\'m trying to achieve this by setting the

相关标签:
2条回答
  • 2020-12-12 11:07

    You should use the flex or flex-basis property rather than width. Read more on MDN.

    .flexbox .red {
      flex: 0 0 25em;
    }
    

    The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

    flex-grow: 0;     /* do not grow   - initial value: 0 */
    flex-shrink: 0;   /* do not shrink - initial value: 1 */
    flex-basis: 25em; /* width/height  - initial value: auto */
    

    A simple demo shows how to set the first column to 50px fixed width.

    .flexbox {
      display: flex;
    }
    .red {
      background: red;
      flex: 0 0 50px;
    }
    .green {
      background: green;
      flex: 1;
    }
    .blue {
      background: blue;
      flex: 1;
    }
    <div class="flexbox">
      <div class="red">1</div>
      <div class="green">2</div>
      <div class="blue">3</div>
    </div>


    See the updated codepen based on your code.

    0 讨论(0)
  • 2020-12-12 11:12

    In case anyone wants to have a responsive flexbox with percentages (%) it is much easier for media queries.

    flex-basis: 25%;
    

    This will be a lot smoother when testing.

    // VARIABLES
    $screen-xs:                                         480px;
    $screen-sm:                                         768px;
    $screen-md:                                         992px;
    $screen-lg:                                         1200px;
    $screen-xl:                                         1400px;
    $screen-xxl:                                        1600px;
    
    // QUERIES
    @media screen (max-width: $screen-lg) {
        flex-basis: 25%;
    }
    
    @media screen (max-width: $screen-md) {
        flex-basis: 33.33%;
    }
    
    0 讨论(0)
提交回复
热议问题