Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make longest flex item set the width for the column

Tags:

html

css

flexbox

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>
like image 971
user3712353 Avatar asked Feb 02 '16 11:02

user3712353


2 Answers

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

like image 99
Michael Benjamin Avatar answered Sep 20 '22 07:09

Michael Benjamin


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;
}
like image 24
Siddharth Avatar answered Sep 21 '22 07:09

Siddharth