简体   繁体   中英

How do I make flex items shrink to their smallest fitting size, but the same size?

I'm trying to make a row of buttons, where the buttons will be the same size, but as small as possible - so each being the same size as the largest button.

How can I do this?

 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> 

flexbox can do a lot but not all. For this grid would be good, but since it lacks good browser support, its older "version" table might be an option.

Here is a script free, dynamic solution, using display: inline-table .

 .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; } 
 <div class="container"> <div class="wrap"> <div class="item">this one is quite long</div> <div class="item">shorter</div> </div> </div> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM