如何让 child 元素流到 parent 之外?

How to make child elements flow outside of parent?

目前我有一个 html 文件,其 DOM 结构如下:

<div id="parent">
  <div class="child"></div>
  <div class="child"></div>
  <div class="child"></div>
</div>

我想要这样的布局:"child" div 浮动在 parent 之外,像 table 单元格一样排在同一行中,每个 child 的宽度都比 parent 大,高度小,它们 child div 将覆盖 parent div 的底部.(我还不能post图片,所以我只能描述它),这必须在不改变DOM结构的情况下完成。

我试图让 child 元素内联块并向左浮动,但它们似乎一直在堆积,有没有办法在不改变 DOM 的情况下实现它?

您可以改用绝对定位:

#parent{
  height:300px; width:300px; position:relative;
}
.child{
  height:100px; width:300px; position:absolute;
}
.child:first-child{
  left:-50px;
}

当然,这只是您需要的CSS的一部分。

我建议改用 flex:

display: flex

它比使用

响应更快
display: block
position: absolute

HTML:

<div id="parent">
  <div class="child">hi</div>
  <div class="child">hello</div>
  <div class="child">hey</div>
</div>

CSS:

#parent {
  display: flex;
  flex-direction: row;
  width: 400px;
}

.child {
  flex-grow: 1;
  height: 30px;
  text-align: center;
  color: white;
}

.child:nth-of-type(1) {
  background:red;
}

.child:nth-of-type(2) {
  background: green;
}

.child:nth-of-type(3) {
  background: purple;
}

这是来自 jsfiddle 的示例: https://jsfiddle.net/pbu05aaL/