Targeting flex items on the last row

2018-12-31 01:27发布

My problem is that I want the flexbox with variable range width, and all works well, but not on the last row. I want the same dimension for all children even where the row is not full of children (the last row).

#products-list {
    position:relative;
    display: flex;
    flex-flow: row wrap;
    width:100%;
}

#products-list .product {
    min-width:150px;
    max-width:250px;
    margin:10px 10px 20px 10px;
    flex:1;
}

In the JSFiddle example I created a dynamic situation.

My flex divs can shrink until 150px and grow up to 250px, but all must be with the same size (and obviously I want a CSS solution, with JS I know the way).

3条回答
宁负流年不负卿
2楼-- · 2018-12-31 01:39

As a fast and dirty solution one can use:

.my-flex-child:last-child/*.product:last-child*/ {
  flex-grow: 100;/*Or any number big enough*/
}
查看更多
何处买醉
3楼-- · 2018-12-31 01:57

Unfortunately, in the current iteration of flexbox (Level 1), there is no clean way to solve the last-row alignment problem. It's a common problem.

It would be useful to have a flex property along the lines of:

  • last-row
  • last-column
  • only-child-in-a-row
  • alone-in-a-column

This problem does appear to be a high priority for Flexbox Level 2:

Although this behavior is difficult to achieve in flexbox, it's simple and easy in CSS Grid Layout:

In case Grid is not an option, here's a list of similar questions containing various flexbox hacks:

查看更多
只若初见
4楼-- · 2018-12-31 01:58

I used this workaround, even if it's not very elegant and it doesn't use the power of Flexbox.

It can be carried out on the following conditions:

  • All the items have the same width
  • The items have a fixed width
  • You use SCSS/SASS (can be avoided though)

If this is the case, you can use the following snippet:

 $itemWidth: 400px;
 $itemMargin: 10px;

html, body {
  margin: 0;
  padding: 0;
}

.flex-container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  margin: 0 auto;
  border: solid 1px blue;
}

@for $i from 1 through 10 {
  @media only screen and (min-width: $i * $itemWidth + 2 * $i * $itemMargin) {
    .flex-container {
      width: $i * $itemWidth + 2 * $i * $itemMargin;
    }
  }
}

.item {
  flex: 0 0 $itemWidth;
  height: 100px;
  margin: $itemMargin;
  background: red;
}
<div class="flex-container">
  <div class="item"></div>
  <div class="item" style="flex: 500 0 200px"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

Here I have created an example on codepen which also implements margin.

The second and the third conditions can be avoided respectively using css variables (if you decided to provide support for it) and compiling the above scss snippet.

Well, it's true, we could do it also before flexbox, but display: flex can be still essential for a responsive design.

查看更多
登录 后发表回答