BFC块级格式化上下文

博客详细探讨了BFC(块格式化上下文)的概念及其作用,包括如何触发BFC,如元素浮动导致的父元素高度塌陷问题,两栏自适应布局的实现,以及垂直方向margin重叠的解决方案。通过设置特定样式属性,如overflow、display或position,可以创建BFC以避免布局影响。文章提供了实例代码展示BFC在实际布局问题中的应用。

BFC的目的


形成一个完全独立的空间,让空间中的子元素不会影响到外面的布局

触发BFC的方式

  • float 除了none以外的值

  • overflow 除了visible 以外的值(hidden,auto,scroll )

  • display (table-cell,table-caption,inline-block, flex, inline-flex)

  • position值为(absolute,fixed)

  • fieldset元素-表单周围的边框说明

BFC到底能干啥

子元素浮动,父元素高度塌陷

			.father,
			.monther {
				width: 600px;
				background-color: #005AA0;
			}
			.son {
				width: 100px;
				height: 100px;
				background-color: #008000;
				float: left;
			}
			.monther {
				height: 200px;
			}
		<div class="father">
			<div class="son"></div>
			<div class="son"></div>
			<div class="son"></div>
			<div class="son"></div>
		</div>
		<div class="monther"></div>

会导致父亲高度为0
在这里插入图片描述

解决办法:触发BFC

  1. 父亲添加高度-只适用于父亲高度确定时
.father {
	height:200px
}
  1. 让父亲也浮动-依然会影响到后边的布局
.father {
	float:left
}
  1. 绝对定位/固定定位【脱离标准流】-依然会影响到后边的布局
.father {
	position: absolute;
}
  1. table-cell/inline-block等
.father {
	display: table-cell/inline-block等;
}
两栏自适应布局-一栏固定,一栏自适应[触发BFC]

解决办法:

自适应的一侧触发BFC即可

垂直方向margin重合

			.friend{
				width: 100px;
				height: 100px;
				background-color: red;
			}
			.friend:first-child{
				margin-bottom: 20px;
			}
			.friend:last-child{
				margin-top: 20px;
			}
<div class="friend"></div>
<div class="friend"></div>

在这里插入图片描述
解决办法:

给第二个div包裹一个父亲,父亲触发BFC即可

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值