如何使柔性项目缩小到最小的拟合尺寸,但尺寸相同?

时间:2016-12-02 03:04:32

标签: html css css3 flexbox

我试图制作一排按钮,按钮的大小相同,但尺寸尽可能小 - 所以每个按钮的大小与最大的按钮相同。

我该怎么做?



div {
  border: solid 1px black;
  margin: 5px;
  padding: 5px;
  background-color: #fff;
}
.container {
  display: flex;
  flex-flow: row nowrap;
  justify-content: flex-end;
}
.item {
  background-color: #eef;
  flex: 0 1 auto;
  white-space: nowrap;
}

<div class="container">
  <div class="item">this one is quite long</div>
  <div class="item">short</div>
</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:4)

flexbox可以做很多事情,但不是全部。对于这个grid会很好,但由于它缺乏良好的浏览器支持,它的旧版本#34;版本&#34; table可能是一种选择。

这是一个使用display: inline-table的免费脚本动态解决方案。

&#13;
&#13;
.container,
.item {
  border: solid 1px black;
  margin: 5px;
  padding: 5px 0 5px 5px;
  background-color: #fff;
}
.container {
  text-align: right;
}
.wrap {
  display: inline-table;
  border-spacing: 10px 5px;
}
.item {
  background-color: #eef;
  display: table-cell;
  width: 50%;
  white-space: nowrap;
  text-align: left;
}
&#13;
<div class="container">
  <div class="wrap">
    <div class="item">this one is quite long</div>
    <div class="item">shorter</div>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

I don't think this is possible with flexbox, but for what it's worth, this can be achieved with the CSS Grid Layout Module.

.container,
.item {
  border: solid 1px black;
  margin: 5px;
  padding: 5px 0 5px 5px;
  background-color: #fff;
}
.container {
  text-align: right;
}
.wrap {
  display: inline-grid;
  grid-template-columns: 1fr 1fr;
}

.item {
  background-color: #eef;
  text-align: left;  
}
<div class="container">
  <div class="wrap">
    <div class="item">this one is quite long</div>
    <div class="item">shorter</div>
  </div>
</div>

Codepen demo

Here's the relevant CSS:

.container {
  text-align: right; 
}
.wrap {
  display: inline-grid; 
  grid-template-columns: 1fr 1fr;
}

It's worth noting here that flex-grow: 1 (for flex items) works a bit different here than flexible lengths - 1fr for css grids.

.container,
.item {
  border: solid 1px black;
  margin: 5px;
  padding: 5px 0 5px 5px;
  background-color: #fff;
}
.container {
  text-align: right;
}
.wrap {
  display: inline-flex;
}

.item {
  background-color: #eef;
  text-align: left;
  flex: 1;
}
<div class="container">
  <div class="wrap">
    <div class="item">this one is quite long</div>
    <div class="item">shorter</div>
  </div>
</div>

It's almost identical code - except that flex-grow seems to wrap the first item's long text on to a new line.