如何使一个相对位置的孩子得到所有父母的高度

How to make a relatively positioned child to get all parent's height

本文关键字:高度 父母 孩子 何使一 相对 位置      更新时间:2023-09-26

我有这样的布局

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的。设置侧边栏的位置为绝对解决了这个问题,但增加了更多的bug,是否有一个解决方案,相对定位的子获得所有的父的高度没有指定父的高度像素?

正如你所看到的,如果#main超过了侧边栏的宽度,侧边栏会变短,但是需要填充所有的高度

CSS Flexbox确实解决了你的问题,如果你不需要支持旧的浏览器,这是一个完美的答案。

基本上,只要将display: flex添加到容器中就可以为您解决这个问题。

浏览器以多种方式支持flexbox,请确保您检查该笔编译的CSS以获取所有浏览器前缀等。

链接到CodePen

您可以使用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>

我猜jQuery解决方案将帮助您解决您的问题:)试试这个,这将允许有#sidebar具有相同的高度作为container。希望这对你有帮助:)编码愉快。

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。希望这能解决问题。这将使侧边栏的高度与主栏高度相同。