簡體   English   中英

如何讓一個相對定位的孩子獲得所有父母的身高

[英]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,以獲取所有瀏覽器的前綴及其類似信息。

鏈接到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解決方案將幫助您解決問題:) 試試這個,這將使#sidebarcontainer具有相同的高度。 希望對您有所幫助:)編碼愉快。

jQuery的:

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

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

編輯:

JS小提琴鏈接

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

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

只需將內容更改為main。 希望這能解決問題。 這將使側邊欄的高度與主高度相同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM