当父母成长/收缩时,广泛的div孩子

时间:2016-05-31 21:28:01

标签: html css

我有这个HTML代码:

<div id="parent">
    <div id="child1">
    </div>
    <div id="child2">
    </div>
</div>

我想要做的是让child2占用200px并且位于父级的底部,并且当父级增长/缩小时(例如,用户放大/缩小页面)让child1增长/缩小

示例:

如果父母的身高是1000px我想要child1身高800px&amp; child2身高200px

如果父母的身高是2000px我想要child1身高1800px&amp; child2身高200px

我该怎么做?

4 个答案:

答案 0 :(得分:1)

您可以使用flexbox完成此操作。但请注意:仅在现代浏览器中受支持,请参阅caniuse

#parent {
  display: flex;
  flex-direction: column;
  min-width: 100%;
  height: 1000px;
  background-color: gray;
}

#child1 {
  flex-grow: 1;
  min-width: 100%;
  background-color: orange;
}

#child2 {
  align-self: flex-end;
  min-width: 100%;
  height: 200px;
  background-color: red;
}
<div id="parent">
    <div id="child1">
    </div>
    <div id="child2">
    </div>
</div>

答案 1 :(得分:1)

根据第二个孩子身高,这个技巧使用第一个孩子的边距和填充:

&#13;
&#13;
#parent {
  height: 1000px;
  background-color: green;
}

#child1 {
  height: 100%;
  background-color: blue;
  margin-bottom: -200px;
  padding-bottom: 200px;
}

#child2 {
  height: 200px;
  background-color: red;
}
&#13;
<div id="parent">
    <div id="child1">
    </div>
    <div id="child2">
    </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

1

要做到这一点非常简单。如果你使child2 200px然后将child1设置为100%的高度减去200px,child1将占用child2正在服用的200px之外的所有空间。

#parent {
  height: 1000px;
  background-color: green;
}

#child1 {
  height: calc(100% - 200px);
  background-color: blue;
}

#child2 {
  height: 200px;
  background-color: red;
}

https://jsfiddle.net/ak8gbjuy/1/

2

您也可以使用javascript

来完成

你取父母的高度,然后是-200。将子1设置为结果高度。

var height = $("#parent").height() -200;
$("#child1").height(height);

https://jsfiddle.net/g9xj0mjx/

如果您因此想要摆脱1000px父级高度并使其成为百分比,那么当用户更改屏幕大小时(如您所述),它会发生变化。你可以将它放在resize事件中

$( window ).resize(function() {
  var height = $("#parent").height() -200;
  $("#child1").height(height);
});

答案 3 :(得分:-1)

<强>解决方法1

您可以使用absolute positionpadding执行此操作:

&#13;
&#13;
html, body {height:100%;margin:0}

#parent {
  height:100%;
  position:relative;
}
#child1 {
  height:100%;
  background:yellow;
  padding-bottom:200px;
  box-sizing:border-box;
}
#child2 {
  height:200px;
  width:100%;
  position:absolute;
  bottom:0;
  left:0;
  background:black;
}
&#13;
<div id="parent">
    <div id="child1">
    </div>
    <div id="child2">
    </div>
</div>
&#13;
&#13;
&#13;

<强>溶液2

您也可以使用calc(),查看support

&#13;
&#13;
html, body {height:100%;margin:0}

#parent {
  height:100%;
}
#child1 {
  height:calc(100% - 200px);
  background:yellow;
}
#child2 {
  height:200px;
  background:black;
}
&#13;
<div id="parent">
    <div id="child1">
    </div>
    <div id="child2">
    </div>
</div>
&#13;
&#13;
&#13;