![](/img/trans.png)
[英]How can I quickly find the relatively positioned HTML parent element of an absolutely positioned child?
[英]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的高度,则我需要侧边栏占据所有可用高度。 将侧边栏位置设置为绝对值可以解决此问题,但是还会添加更多错误,是否有一种相对定位的子项能够获得所有父项的高度而无需指定父级像素高度的解决方案?
正如您在小提琴中看到的那样,如果#main超过侧边栏的宽度,则侧边栏会变短,但是它需要填充所有高度。
CSS Flexbox确实可以解决您的问题,如果您不必支持旧版浏览器,CSS Flexbox就是一个完美的答案。
基本上,只需将display: flex
添加到容器中,即可为您解决这个问题。
浏览器以多种方式支持flexbox,请确保您检查了Pen的已编译CSS,以获取所有浏览器的前缀及其类似信息。
您可能可以结合使用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);
});
编辑:
$(document).ready(function(){
var wrapH = $('#main').outerHeight();
$('#sidebar').css("height", wrapH);
});
只需将内容更改为main。 希望这能解决问题。 这将使侧边栏的高度与主高度相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.