父级DIV如何从子级DIV继承宽度(百分比)

4
我目前正试图找出一种方式,可以拥有一个以内容为导向的从底部向上调整大小的布局。
我的情况如下:https://codepen.io/Flash1232/pen/JJYPVQ 很明显,这里的问题是div不包含在div中。现在是否有任何解决方案,只涉及纯CSS和HTML,或者我必须编写JS,例如“将包装器宽度设置为其内部div的宽度”?
感谢提前提供任何线索!

1
你需要使用JS来实现。CSS无法向上遍历树形结构。 - Gerard
3个回答

3

我用父元素的 display:flex 解决了我的问题 :)


1

您可能希望考虑使用flexbox。请参见下文。如果有任何需要不同的地方,请告诉我。

.outer-div {
  position: absolute;
  background: black;
  width: 800px;
  left: 0;
  top: 0;
  bottom: 0;
  overflow: auto;
  padding: 10px;
}

.area {
  overflow: auto;
  display: flex;
  border: 5px solid red;
  background: white;
  margin: 10px 40px 10px 10px;
}

.column {
  background: green;
  border: 5px solid blue;
}

.wrapper {
  display: flex;
  border: 5px solid yellow;
  justify-content: center;
  align-items: center;
}

.table {
  white-space: nowrap;
}

.violet {
  background: violet;
  width: 120%;
  height: 80px;
}

.red {
  background: red;
  width: 150%;
  height: 80px;
  margin-bottom: 20px;
}

.icons {
  Background: yellow;
  float: right;
  height: auto;
  width: auto;
}
<div class="outer-div">
  <div class="area">
    <div class="column">
      <div class="wrapper">
        <div class="table red">
          <span>***Table Content***</span>
        </div>
      </div>
      <div class="wrapper">
        <div class="table violet">
          <span>***Table Content***</span>
        </div>
      </div>
    </div>
    <div class="column">
      <div class="wrapper">
        <div class="table violet">
          <span>***Table Content***</span>
        </div>
      </div>
    </div>
  </div>
  <div class="icons">
    <p>Icon</p>
    <p>Icon</p>
    <p>Icon</p>
    <p>Icon</p>
    <p>Icon</p>
    <p>Icon</p>
  </div>
</div>


我还应该提到内部表格的宽度百分比必须考虑在内,并且包装器应该围绕它们的额外宽度进行包装,因此“column” DIV应该适合该大小。 - Flash1232

0
你应该阅读 width 属性的定义。

https://developer.mozilla.org/en/docs/Web/CSS/width

百分比:指的是包含块的宽度。 如果您将宽度设置为150%,则明确表示子元素应该比父元素更大。如果您强制使子元素更宽,则不能期望父元素具有与子元素相同的宽度。

知道这点很好。我如何使包装器包装内容(并使列与包装器的宽度匹配),同时仍然能够将表格的宽度设置为其自身宽度的百分比? - Flash1232
“Own width”是什么?如果没有指定宽度,它是浏览器为内容计算的宽度吗?如果列应比必要的宽,则指定边框、边距或填充。 - ceving
“Own width” 的确意味着表格的内容。 - Flash1232

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接