user3712353
user3712353

Reputation: 4201

Make longest flex item set the width for the column

I have multiple divs. Inside each I have label and span.

I want the labels' width to be set by the longest label, and the spans will all start at the same point.

.container {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
<article>
  <div class="container">
    <label class="key">text</label>
    <span class="value">text</span>
  </div>
</article>

Upvotes: 10

Views: 3619

Answers (3)

Michael Benjamin
Michael Benjamin

Reputation: 371003

If you want to use flexbox for this layout, you'll need to restructure your HTML.

Flex items can share equal heights / widths, but only if they are siblings.

article {
  display: flex;
}

.container {
  display: flex;
  flex-direction: column;
}

/* non-essential decorative styles */
.key { background-color: aqua; }
.value { background-color: pink; }
.container > * { margin: 2px; padding: 2px; border: 1px solid #999; }
<article>
  <div class="container">
    <label class="key">label label label label</label>
    <label class="key">label</label>
    <label class="key">label</label>
    <label class="key">label</label>
  </div>
  <div class="container">
    <span class="value">span span span span</span>
    <span class="value">span</span>
    <span class="value">span</span>
    <span class="value">span</span>
  </div>
</article>

jsFiddle demo

Upvotes: 6

zgabievi
zgabievi

Reputation: 1202

You can simply use display: table:

HTML:

<article>
    <div class="container">
        <label class="key">text</label>
        <span class="value">text</span>
    </div>

    <div class="container">
        <label class="key">texttexttexttext</label>
        <span class="value">longgggg text</span>
    </div>

    <div class="container">
        <label class="key">tetexttextxt</label>
        <span class="value">test text</span>
    </div>

    <div class="container">
        <label class="key">texttext</label>
        <span class="value">text</span>
    </div>
</article>

CSS:

.article {
  display: table;
}

.container {
  display: table-row;
}

label {
  display: table-cell;
  background-color: aqua;
}

span {
  display: table-cell;
  background-color: orange;
}

Fiddle

Upvotes: 0

Siddharth
Siddharth

Reputation: 869

try this fiddle,

I changed display:flex to 'table-row' to attain same width of .container, and then used this CSS

.container{
    display:table-row;

}
label{
  display: table-cell;
   border:solid 1px red;
}
span{
  display: table-cell;
  border:solid 1px blue;
}

Upvotes: 3

Related Questions