我有一个类似这样的页面结构:

<body>
  <div id="parent">
    <div id="childRightCol">
      /*Content*/
    </div>
    <div id="childLeftCol">
      /*Content*/
    </div>
  </div>
</body>

我想为父div扩大高度时,内部div的高度增加。

编辑: 一个问题是,如果子内容的宽度扩展超过浏览器窗口的宽度,我目前的CSS把一个水平滚动条上的父div。我希望滚动条是在页面级别。目前我的父div被设置为溢出:auto;

你能帮我做这个的CSS吗?


当前回答

这是规范所描述的功能-这里的几个答案是有效的,并与以下内容一致:

If it has block-level children, the height is the distance between the top border-edge of the topmost block-level child box that doesn't have margins collapsed through it and the bottom border-edge of the bottommost block-level child box that doesn't have margins collapsed through it. However, if the element has a nonzero top padding and/or top border, or is the root element, then the content starts at the top margin edge of the topmost child. (The first case expresses the fact that the top and bottom margins of the element collapse with those of the topmost and bottommost children, while in the second case the presence of the padding/border prevents the top margins from collapsing.) Similarly, if the element has a nonzero bottom padding and/or bottom border, then the content ends at the bottom margin edge of the bottommost child.

网址:https://www.w3.org/TR/css3-box/#blockwidth

其他回答

如果你在#childRightCol和#childRightCol中的内容是向左或向右浮动的,只需将其添加到css中:

#childRightCol:before { display: table; content: " "; }
#childRightCol:after { display: table; content: " "; clear: both; }
#childLeftCol:before { display: table; content: " "; }
#childLeftCol:after { display: table; content: " "; clear: both; }

对于那些不能从这个答案中找到答案的人:

尝试设置填充值大于0,如果子div有margin-top或margin-bottom,你可以用填充替换它

例如,如果你有

#childRightCol
{
    margin-top: 30px;
}
#childLeftCol
{
    margin-bottom: 20px;
}

最好将其替换为:

#parent
{
    padding: 30px 0px 20px 0px;
}

使用height: auto或在父元素上使用min-height都可以。为了避免水平滚动条,可以通过在子元素上使用box-sizing: border-box或在父元素上使用overflow: hidden来避免由于填充或边框而导致的水平滚动条。 至于水平滚动条由于宽度的身体,如果你是使用宽度:100vw代替宽度:100%。

这是你想要的吗?

.childRightCol, .childLeftCol
{
    display: inline-block;
    width: 50%;
    margin: 0;
    padding: 0;
    vertical-align: top;
}

下面的代码对我有用。

css

.parent{
    overflow: auto;
} 

html

<div class="parent">
    <div class="child1">
    </div>
    <div class="child2">
    </div>
    <div id="clear" style="clear:both;"></div>
</div>