Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
515 views
in Technique[技术] by (71.8m points)

html - All widths set to width of widest element

I've read a lot of tutorials about CSS flex boxes and CSS grids, but frankly I just can't figure out how to do this simple(?) thing.

All I want is for the elements in a container to all be as wide as the widest element.

I don't want them to fill up the whole width of the container, just all grow to the maximum width. Can that be done with CSS?

Consider this HTML:

<div class="container">
   <button>a normal button</button>
   <button>tiny</button>
   <button>a really, really, really wide button</button>
</div>

That produces something like this:

enter image description here

What I want is something like this, where they're all the width of that widest button:

enter image description here

I DON'T want them to just stretch out to fill the width of the page:

enter image description here

Can this be done? If so, what would be the CSS for the above HTML?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yes. This can be done with pure CSS.

Here's a simple solution:

.container {
  display: inline-grid;
  grid-template-columns: 1fr 1fr 1fr;
}
<div class="container">
   <button>a normal button</button>
   <button>tiny</button>
   <button>a really, really, really wide button</button>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...