您的位置:首页 > Web前端 > CSS

CSS让子元素div的高度填满父容器的剩余空间的方法

2021-03-15 04:00 1436 查看

1.使用浮动的方式

效果图:

代码如下:(注意,此时.content的高度是500px,即父元素的高度,但是浮动元素在 .content 上方,盖住了 .content,将 .nav背景样式改为 background-color: rgba(0,0,0,0.1);可观察到效果)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>高度充满父容器</title>
</head>
<style>
.parent {
height: 500px;
width: 300px;
border: 1px solid red;/***/
padding: 2px 2px;/***/
}
.nav {
height: 100px;
width: 100%;/*必须,沾满宽度防止浮动 */
float: left;/*必须 */
background-color: red;
}
.content {
height:100%;/*必须*/
background-color: green;
}
</style>
<body>
<div class="parent">
<div class="nav">
固定高度
</div>
<div class="content">
自适应父容器, 充满剩余的空间
</div>
</div>
</body>
</html>

2.使用定位

代码如下:(推荐使用此种方法,没有上面的那种方法的缺点)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>高度充满父容器</title>
</head>
<style>
.parent {
position: relative;
height: 500px;
width: 300px;
border: 1px solid red;/***/
padding: 2px 2px;/***/
}
.nav {
height: 100px;
width: 100%;
background-color: red;
}
.content {
position:absolute;
top: 100px;
bottom: 0px;
background-color: green;
width: 100%;
}
</style>
<body>
<div class="parent">
<div class="nav">
固定高度
</div>
<div class="content">
自适应父容器, 充满剩余的空间
</div>
</div>
</body>
</html>

到此这篇关于CSS让子元素div的高度填满父容器的剩余空间的方法的文章就介绍到这了,更多相关CSS子元素div高度填满剩余空间内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息