弹性项目的子元素宽度相同

Same width for child elements of flex items

我正在尝试找到一种使用 flexbox 重新创建 colspan 的方法。

这是我想要实现的一个简单示例:https://jsfiddle.net/4b63b1ze/

<table style="width: 100%">
    <tr>
        <td rowspan="2">azerty</td>
        <td colspan="2">azerty</td>
        <td rowspan="2">azerty</td>
    </tr>
    <tr>
        <td>azerty</td>
        <td>azerty</td>
    </tr>
</table>

这是我目前拥有的:https://jsfiddle.net/pudxj9sy/

html:

<div class="container">
    <div class="item">azerty</div>
    <div class="item">
        azerty
        <div class="item">azerty</div>
        <div class="item">azerty</div>
    </div>
    <div class="item">azerty</div>
    <div class="item">azerty</div>
</div>

风格:

.container {
    border: 1px solid red;
    display: flex;
}

.item {
    flex-grow: 1;
    flex-basis: 0;
    border: 1px solid gray;
}

所以理论上我必须将第二项的flex-grow设置为2。但是由于内容是动态添加的,所以我不想依赖通过js/jQuery添加样式属性。

有没有可能只通过css?

您需要使用嵌套的 flexboxes。

HTML

<div class="container">
    <div class="item">azerty</div>
    <div class="item">
           <div class="item2">azerty</div>
           <div class="container-inner2">
              <div class="item3">azerty</div>
              <div class="item3">azerty</div>
           </div>    
    </div>
    <div class="item">azerty</div>
</div>

CSS

.container {
    display: flex; /* primary flex container */
    height: 100px; /* for demo purposes */
    border: 1px solid red; /* for demo purposes */
}

.item {
    display: flex; /* flex items declared flex containers, as well */
    justify-content: center; /* center-align flex items (horizontally, in this case) */
    flex: 1; /* flex items take up all available space */
    border: 1px solid gray; /* for demo purposes */
    margin: 2px;  /* for demo purposes */
}

.item:nth-child(2) { 
    flex-direction: column; /* middle item changes direction from row */
    flex-grow: 2; /* middle column gets 2x available space than siblings */
    text-align: center; /* one less nested flexbox (.item2) */
    border: none;  /* remove redundant border */
    margin: 0; /* remove redundant margin */
}

.item2 {
    flex: 1; /* take all available space */
    border: 1px solid gray;
    margin: 2px;
}

.container-inner2 {
    display: flex; /* nested flexbox; flex-direction back to row (by default) */
    flex: 1;  /* take all available space */
}
.item3 {
    flex: 1; /* available space distributed evenly among flex items */
    border: 1px solid gray;
    margin: 2px;
  }

演示:https://jsfiddle.net/pudxj9sy/5/