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

建站知识 2021-07-02 23:04www.168986.cn长沙网站建设

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高度填满剩余空间内容请搜索狼蚁SEO以前的文章或继续浏览狼蚁网站SEO优化的相关文章,希望大家以后多多支持狼蚁SEO!

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by

长沙网络推广|微博营销|长沙seo优化|视频营销|长沙网络营销|微信营销|长沙网站建设|口碑营销|软文营销