最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Make a column take up available space in a flex container with wrap - Stack Overflow

programmeradmin2浏览0评论

I have a layout like this:

.container {
  background-color: yellow;
  display: flex;
  flex-wrap: wrap;
}

.col-x {
  flex: 0 0 5rem;
  background-color: red;
}

.col-y {
  flex: 1 0 auto;
  background-color: green;
}
<div class="container">
  <div class="col-x">X</div>
  <div class="col-y">Y</div>
  <div class="col-x">X</div>
  <div class="col-y">Y</div>
</div>

I have a layout like this:

.container {
  background-color: yellow;
  display: flex;
  flex-wrap: wrap;
}

.col-x {
  flex: 0 0 5rem;
  background-color: red;
}

.col-y {
  flex: 1 0 auto;
  background-color: green;
}
<div class="container">
  <div class="col-x">X</div>
  <div class="col-y">Y</div>
  <div class="col-x">X</div>
  <div class="col-y">Y</div>
</div>

  1. Container width is variable
  2. col-x is fixed width
  3. col-y should should take up the remaining space so that col-x always starts at a new row

col-y is not taking up the full available width with "flex: 1 0 auto". If I set the width of col-y to 100% it wraps to a new row, which is not what I want.

See: https://codepen.io/saurabh0/pen/GgRxVja

Share Improve this question edited Mar 20 at 13:47 Ori Drori 194k32 gold badges238 silver badges229 bronze badges asked Mar 20 at 13:46 SaurabhSaurabh 1254 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 3

The 2 columns layout can be easily achieved using CSS grid:

.container {
  background-color: yellow;
  display: grid;
  grid-template-columns: auto 1fr;
}

.col-x {
  width: 5rem;
  background-color: red;
}

.col-y {
  background-color: green;
}
<div class="container">
  <div class="col-x">X</div>
  <div class="col-y">Y</div>
  <div class="col-x">X</div>
  <div class="col-y">Y</div>
</div>

If you must use a flexbox, set the width of .col-y with calc(100% - 5rem) (100% - .col-x width):

.container {
  background-color: yellow;
  display: flex;
  flex-wrap: wrap;
}

.col-x {
  width: 5rem;
  background-color: red;
}

.col-y {
  width: calc(100% - 5rem);
  background-color: green;
}
<div class="container">
  <div class="col-x">X</div>
  <div class="col-y">Y</div>
  <div class="col-x">X</div>
  <div class="col-y">Y</div>
</div>

 <div className="d-flex flex-wrap gap-4">
      <div className="flex-fill bg-success text-white p-4 text-center">Item 1</div>
      <div className="flex-fill bg-success text-white p-4 text-center">Item 2</div>
      <div className="flex-grow-1 bg-danger text-white p-4 text-center">
        Item 3 (This will take up remaining space)
      </div>
      <div className="flex-fill bg-success text-white p-4 text-center">Item 4</div>
      <div className="flex-fill bg-success text-white p-4 text-center">Item 5</div>
    </div>

useing bootstep css

发布评论

评论列表(0)

  1. 暂无评论