如何使一个相对位置的孩子得到所有父母的高度
How to make a relatively positioned child to get all parent's height
我有这样的布局
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
。希望这对你有帮助:)编码愉快。
$(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。希望这能解决问题。这将使侧边栏的高度与主栏高度相同。
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- ExtJS——在展开/折叠时调整面板高度
- 分析高度属性时出现意外值{{specs.height}}.index.html
- 单击页面上的链接后高度发生变化
- 不加载宽度和高度的角度pintura
- 查找元素高度,包括边距
- 如何自动调整标签的高度以适应内容
- Javascript高度问题
- 使用JavaScript根据窗口/视口的高度动态调整图像大小
- 如何计算每个元素's的高度,并将这些值用作函数中的变量
- 如果宽度是百分比,如何设置以px为单位的图像高度
- 通过jquery设置最小高度
- 文档就绪提供了错误的选择器高度
- 调整缩放窗口高度提升缩放
- 根据图像高度添加类
- 检测非移动页面上的移动设备屏幕宽度和高度
- 更改代码镜像中TextArea的高度和宽度
- 获取iframe内容的宽度-高度
- 父母是绝对的;仅当滚动条超过父对象的高度限制时,才为子对象提供滚动条
- 如何使一个相对位置的孩子得到所有父母的高度