【面试题】BFC详解

1. BFC

Block format context(BFC)表示块级格式上下文,它是CSS中的一种布局模式,用来决定块级元素如何布局以及与其他元素的关系。BFC是一个独立的布局环境,BFC内部的元素的渲染不会影响到边界以外的元素,并且BFC中的元素会按照一定的规则进行布局。

2. BFC的布局规则

  • BFC中的所有元素垂直排列,即每个元素从上到下排列,元素之间的垂直距离由 margin 决定,同一个 BFC 中的相邻元素之间的 margin 会发生重叠。
  • 每个块的左外边框紧贴包含块的左边框。
  • 开启了BFC的元素和浮动元素不会重叠,会挨着浮动元素显示。
  • BFC是一个独立的渲染区域,内部元素的布局不会影响外部元素的布局。
  • 计算BFC高度时,浮动子元素也参与运算。

3. 触发BFC的方式

  • HTML根元素自动触发BFC;
  • 浮动的元素;
  • 定位的元素,position:absoluteposition:fixed
  • display:inline-block/flex/table-cell-inline-flxe
  • overflow: hidden

4. 利用BFC清除浮动

在元素中添加overflow:hidden;样式来清除浮动

<style type="text/css">
    .container{
        background-color: #f1f1f1;
    }
    .left{
        float: left;
    }
    .bfc{
        overflow: hidden;
    }
</style>

<div class="container bfc">
    <img src="https://profile-avatar.csdnimg.cn/default.jpg!1" class="left" style="margin-right: 10px">
    <p class="bfc">我是一段文字。。。</p>
</div>

清除浮动前,图片脱离文档流
在这里插入图片描述
清除浮动后,图片撑开容器
在这里插入图片描述

5. BFC解决margin塌陷问题

<style>
	.top{width: 300px; height: 300px; background-color: red; margin-bottom: 100px}
	.bottom{width: 300px; height: 300px; background-blue: red; margin-top: 200px}
</style>

<body>
	<div class = "top"></div>
	<div class = "bottom"></div>
</body>

因为top和bottom这两个div都存在于根html中,所以这两个div处于同一个BFC,它们之间会发生margin塌陷。两个块之间的margin距离为较大的那个margin值,即200px。
在这里插入图片描述
将其中一个块放入另一个开启了BFC的区域中之后,就可以解决margin塌陷问题。

<style>
	.top{width: 300px; height: 300px; background-color: red; margin-bottom: 100px}
	.bottom{width: 300px; height: 300px; background-color: blue; margin-top: 200px}
	.bfc{overflow: hidden}
</style>

<body>
	<div class = "bfc">
		<div class = "top"></div>
	</div>
	<div class = "bottom"></div>
</body>

在这里插入图片描述

6. 利用BFC实现双栏布局

双栏布局:左边宽度固定,右边宽度自适应(随着屏幕的缩放而缩放)

<style>
	.top{background-color: red; width: 200px; height: 200px; float: left;}
	.bottom{height: 300px; background-color: blue; overflow: hidden;}
</style>

<body>
	<div class = "top"></div>
	<div class = "bottom"></div>
</body>

在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

周兴

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值