使行扩展到可滚动父级的宽度

Make rows expand to scrollable parent's width

我正在使用 flexbox 制作类似 table 的布局。
它有主体、行和单元格。
单元格具有以像素为单位的固定宽度。
正文应该可以水平滚动。

我希望行的宽度与单元格的累积宽度相同。

这是codepen

<div class="grand-parent">
  <div class="parent">
    <div class="child">Child 1</div>
    <div class="child">Child 2</div>
    <div class="child">Child 3</div>
  </div>
<div>

有没有办法只使用 CSS 来做到这一点?

P.S。我知道我可以使用 JS 计算宽度并将其设置为父级,或者我可以将背景色设置为祖父级以使其看起来更好,但这不是我在这里需要的。

一种方法是不固定 child 组件的大小,而是使用 flex-grow: 1; 让它们占用所有可用的大小

.child {
      flex-grow: 1;
      color: white;
      background: blue;
      border: 1px solid black;
    }

如果您想强制容器采用 child 宽度,您必须:

  • .child 有 display: inline-flex;

  • .parent有 width: max-content;

    .parent {
       background: red;
       padding: 2em 0;
       width: max-content;
    }
    
    .child {
       display: inline-flex;
       width: 300px;
       color: white;
       background: blue;
       border: 1px solid black;
    }
    

关注此回复的 运行 片段

.grand-parent {
      width: 800px;
      overflow: auto;
    }
    
    .parent {
      display: flex;
      background: red;
      padding: 2em 0;
    }

    .child {
      flex-grow:1;
      color: white;
      background: blue;
      border: 1px solid black;
    }
    
    .parent2 {
      background: red;
      padding: 2em 0;
      width: max-content;
      
    }

    .child2 {
      display: inline-flex;
      width: 300px;
      color: white;
      background: blue;
      border: 1px solid black;
    }

    ::-webkit-scrollbar {
      -webkit-appearance: none;
      width: 7px;
    }

    ::-webkit-scrollbar-thumb {
      border-radius: 4px;
      background-color: rgba(0, 0, 0, .5);
      box-shadow: 0 0 1px rgba(255, 255, 255, .5);
    }
<h1> child take width of parent</h1>
<div class="grand-parent">
  <div class="parent">
    <div class="child">Child 1</div>
    <div class="child">Child 2</div>
    <div class="child">Child 3</div>
  </div>
<div>

<h1> parent take width of child</h1>

<div class="grand-parent">
  <div class="parent2">
    <div class="child2">Child 1</div>
    <div class="child2">Child 2</div>
    <div class="child2">Child 3</div>
  </div>
  <div class="parent2">
    <div class="child2">Child 1</div>
    <div class="child2">Child 2</div>
    <div class="child2">Child 3</div>
  </div>
<div>

好吧,就像 Jeremy 的回答一样,您可以将它们设置为可用 space

您可以将 parent 设置为固定宽度,而不是使 grand-parent 固定宽度;

.parent {
  display: flex;
  background: red;
  padding: 2em 0;
  width: 800px;
  overflow: auto;
}

我采用了 grand-parent 的所有样式并添加到 parent

的样式中

以下代码片段运行良好:

.parent {
  display: flex;
  background: red;
  padding: 2em 0;
  width: 800px;
  overflow: auto;
}

.child {
  flex: 0 0 300px;
  color: white;
  background: blue;
  border: 1px solid black;
}
<div class="grand-parent">
  <div class="parent">
    <div class="child">Child 1</div>
    <div class="child">Child 2</div>
    <div class="child">Child 3</div>
  </div>
</div>