這篇文章主要介紹了CSS子元素跟父元素的高度一致的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
絕對(duì)定位方法:
(1)將父元素設(shè)置為相對(duì)定位,不寫父元素的高度時(shí),會(huì)隨著左邊的子元素高度變化而變化
.parent {
 /*關(guān)鍵代碼*/
 position: relative;
 
 /*其他樣式*/
 width: 800px;
 color: #fff;
 font-family: "Microsoft Yahei";
 text-align: center;
}
(2)左邊一個(gè)元素有個(gè)最小高度的情況
.left {
 min-height: 700px;
 width: 600px;
}
(3)右邊元素要想跟父元素的高度是一致,那么可以用絕對(duì)定位這樣設(shè)置,如果不想同時(shí)寫top和bottom,寫一個(gè)時(shí),再寫上height:100%,也可以達(dá)到一樣的效果
.right {
 /*關(guān)鍵代碼*/
 width: 200px;
 position: absolute;
 top: 0;
 right: 0;
 bottom: 0;
 
 /*其他樣式*/
 background: #ccc;
 
}
(4)完整例子代碼:
<!DOCTYPE html>
<html >
<head>
 <meta charset="UTF-8">
 <title>子元素高度與父元素一致</title>
 <style>
.parent{
 position: relative;
 background: #f89;
width: 800px;
 color: #fff;
 font-family: "Microsoft Yahei";
 text-align: center;
 }
 .left {
 min-height: 700px;
 width: 600px;
}
 .right {
 width: 200px;
 position: absolute;
 top: 0;
 right: 0;
 bottom: 0;
background: #ccc;
 
 }
 </style>
</head>
<body>
 <div class="parent">
 <div class="left">
 左側(cè) left 不定高,parent的高度隨著左側(cè)left 的高度變化而變化,右側(cè)也跟著變
 </div>
 <div class="right">
 這邊的高度跟父元素高度一致
 </div>
 </div>
</body>
</html>
左側(cè) left 不定高,parent的高度隨著左側(cè)left 的高度變化而變化,右側(cè)也跟著變
這邊的高度跟父元素高度一致
(5)效果

(6)問題來了:
如果右側(cè)的子元素高度超出了.parent,怎么辦?
right的子元素,高度為1024px,會(huì)撐破容器,給.right加上 overflow:auto 就防止溢出了
.right-inner {
 background: limegreen;
 height: 1024px;
}
效果圖如下:

完整代碼:
<!DOCTYPE html>
<html >
<head>
 <meta charset="UTF-8">
 <title>子元素高度與父元素一致</title>
 <style>
.parent{
 position: relative;
 background: #f89;
width: 800px;
 color: #fff;
 font-family: "Microsoft Yahei";
 text-align: center;
 }
 .left {
 min-height: 700px;
 width: 600px;
}
 .right {
 width: 200px;
 position: absolute;
 top: 0;
 right: 0;
 height: 100%;
overflow: auto;
background: #ccc;
 
 }
 .right-inner {
 background: limegreen;
 height: 1024px;
 }
 </style>
</head>
<body>
 <div class="parent">
 <div class="left">
 左側(cè) left 不定高,parent的高度隨著左側(cè)left 的高度變化而變化,右側(cè)也跟著變
 </div>
 <div class="right">
 <div class="right-inner">right的子元素,高度為1024px,會(huì)撐破容器,給.right加上 overflow:auto 就防止溢出了</div>
 </div>
 </div>
</body>
</html>
左側(cè) left 不定高,parent的高度隨著左側(cè)left 的高度變化而變化,右側(cè)也跟著變
right的子元素,高度為1024px,會(huì)撐破容器,給.right加上 overflow:auto 就防止溢出了
(7)其他資源
http://stackoverflow.com/questions/3049783/how-to-make-a-floated-div-100-height-of-its-parent
文章來源:腳本之家,原文鏈接:https://www.jb51.net/css/743410.html
申請創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!
 
       
      



