css中父元素没有高度,子元素高度填满

一、问题:

如下代码,父元素father使用flex布局,不设高度,子元素son2高度设置为200px,子元素son2撑开了父元素father,son1无法填满父级元素高度。

<body>
	<div class="father">
		<div class="son1">这是子元素son1</div>
		<div class="son2">这是子元素son2</div>
	</div>
</body>
<style>
	.father{
		display:flex;
		justify-content:space-between;
	}
	.son1{
		
	}
	.son2{
		height:200px;
	}
</style>

二、方法:

要使子元素son1高度填满整个父元素father的高度,就要做一下改变

<body>
	<div class="father">
		<div class="son1">这是子元素son1</div>
		<div class="son2">这是子元素son2</div>
	</div>
</body>
<style>
	.father{
		display:flex;
		justify-content:space-between;
		align-items:stretch;//改变
	}
	.son1{
		height:inherit;//改变
		display: flex;//改变,为了使文字上下居中
        align-items: center;//改变,为了使文字上下居中
        justify-content: center;//改变,为了使文字上下居中
	}
	.son2{
		height:200px;	
	}
</style>

三、总结:

  1. align-items: stretch;属性让当前元素拉升至父级元素的高度或者宽度
  2. height:inherit;属性继承父元素的高度
  3. display: flex;align-items: center;justify-content: center;让文本节点上下居中

版权声明:本文为qq_42858057原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。