machineghost machineghost - 3 months ago 10
CSS Question

CSS: How to enforce width inside a dynamic width container?

First off, here's the fiddle: https://jsfiddle.net/u8v3rgyt/1/

The basic scenario is this: I have some text, which will vary in length. Below this text I have a column of (EDIT: a varying number of) buttons, which also have text that varies. What I want is for the text to control the overall width, and then have the button column adjust its width/its buttons' width in response. In other words, for two different sizes of text, I'm trying to achieve the following:

// Short text
La la la la
[Button 1
text]
[Button 2
with long
text]

// Longer text
La la la la la la la la la la
[Button 1 text]
[Button 2 with long text]


but I get:

// Short text
La la la la
[Button 1 text]
[Button 2 with long text]


I feel like I'm close, but I can't get the button container to have the correct width (and thus I can't limit my buttons' width). Or rather, I can, but to do so I have to put a fixed width on the text, and that doesn't work because I need the whole thing to adjust it's size based on the text.

Any help would be appreciated.

Answer

As I understand, you want the text to dictate the width of the area in which the buttons are laid out. Using the CSS3 flex box model you could do something along these lines:

See this fiddle

HTML

<div class="container">
  <p>Some text blah blah blah, blah blah blah</p>
  <div class="inner">
    <button>Button 1</button>
    <button>Button 2</button>
  </div>
</div>

CSS

.container {
  display: inline-block;
  border: 1px solid red;
  margin-bottom: 24px;
}

.inner {
  display: flex;
  flex-wrap: wrap;
}

button {
  flex-grow: 1;
}