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

发布时间:2022-04-13 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了CSS让子元素div的高度填满父容器的剩余空间的方法脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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高度填满剩余空间内容请搜索脚本宝典以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本宝典!

脚本宝典总结

以上是脚本宝典为你收集整理的CSS让子元素div的高度填满父容器的剩余空间的方法全部内容,希望文章能够帮你解决CSS让子元素div的高度填满父容器的剩余空间的方法所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。