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>

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;
}

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>

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

链接地址: http://www.djcxy.com/p/90082.html

上一篇: 使用反向采样从分布函数生成随机变量

下一篇: 使最长的弹性项目设置列的宽度