如何让一个相对定位的孩子获得所有父母的身高

时间:2015-05-18 08:01:27

标签: javascript jquery html css

我有这个布局

body, html {
  height: 90%;
}
#content{
  width: 100%;
  height: 100%;
}

#sidebar {
  position: relative;
  width: 200px;
  float: left;
  height: 100%;
  background-color: green;
}
#sidebar-content {
  height: 120px;
  background-color: blue;
  
}
#sidebar-footer {
  position: absolute;
  bottom: 0;
  height: 50px;
  width: 100%;
  background-color: black;
}

#main {
  position: relative;
  overflow: hidden;
  background-color: red;
}
#main-content {
   height: 750px;
}
<div id="content">
  <div id="sidebar">
    <div id="sidebar-content">
    </div>
    <div id="sidebar-footer">
    </div>
  </div>
  <div id="main">
    <div id="main-content">
    </div>
  </div>  
</div>

如果它的高度低于#main的高度,我需要侧边栏占据所有高度。将侧边栏位置设置为绝对可以解决这个问题,但是添加更多错误,是否有一个解决方案让相对定位的子项获得所有父级的高度而不用指定父级的高度(以像素为单位)?

正如你在小提琴中看到的那样,如果#main超过侧边栏的宽度,侧边栏会更短,但需要填充所有高度。

3 个答案:

答案 0 :(得分:1)

CSS Flexbox确实解决了您的问题,如果您不必支持旧浏览器,它就是完美的答案。

基本上,只需将display: flex添加到容器中即可为您排序。

浏览器以各种方式支持flexbox,请确保检查该Pen的已编译CSS以获取所有浏览器预修复等。

Link to CodePen

答案 1 :(得分:1)

您可以使用css属性的组合来实现您的目标。您遇到position:absolute问题的主要原因是float:left

快速浏览一下,您可能会发现一些在您的实现中有用的定位和宽度声明:

body,
html {
  height: 90%;
}
#content {
  width: 100%;
  height: 100%;
  position: relative;
  background: lightgray;
}
#sidebar {
  position: absolute;
  width: 200px;
  height: 100%;
  top: 0;
  left: 0;
  background-color: green;
  z-index: 8;
}
#sidebar-content {
  height: 120px;
  background-color: blue;
}
#sidebar-footer {
  position: absolute;
  bottom: 0;
  height: 50px;
  width: 100%;
  background-color: black;
}
#main {
  overflow: hidden;
  background-color: red;
  height: 100%;
  position: absolute;
  top: 0;
  left: 200px;
  width: calc(100% - 200px);
  height: 100%;
  z-index: 10;
}
#main-content {}
<div id="content">
  <div id="sidebar">
    <div id="sidebar-content">
    </div>
    <div id="sidebar-footer">
    </div>
  </div>
  <div id="main">
    <div id="main-content">this is the main content
    </div>
  </div>
</div>

答案 2 :(得分:0)

我想jQuery解决方案将帮助您解决问题:) Try this这将允许#sidebarcontainer具有相同的高度。希望这有助于:)快乐的编码。

jQuery的:

$(document).ready(function(){
    var wrapH = $('#content').outerHeight();

    $('#sidebar').css("height", wrapH);
});

编辑:

JS Fiddle Link

$(document).ready(function(){
    var wrapH = $('#main').outerHeight();

    $('#sidebar').css("height", wrapH);
});

只需将内容更改为main即可。希望这能解决问题。这将使侧栏高度与主高度相同。