清除浮动


提问:

浮动会让元素塌陷。即被浮动元素的父元素不具有高度。例如一个父元素包含了浮动元素,它将塌陷具有零高度。你可以按以下哪种方法处理浮动的影响呢?



# 回答:

1. 添加空标签法:

在最后添加一个空标签元素,然后设置这个空标签的清除浮动属性为:清除2侧浮动;

<style>
.float {
    width: 500px;
    background-color: pink;
}
.one {
    width: 100px;
    height: 100px;
    background-color: #E67474;
}
.two {
    width: 200px;
    height: 200px;
    background-color: #96C143;
}
.one,
.two {
    float: left;
}
.clear {
    clear: both;
}
</style>

<body>
    <div class="float">
        我孩子浮动了
        <div class="one">浮动1</div>
        <div class="two">浮动2</div>
        <div class="clear"></div>
	</div>
</body>

2. 给父元素添加 overflow

<style>
.float {
    width: 500px;
    background-color: pink;
    overflow: hidden;
}
.one {
    width: 100px;
    height: 100px;
    background-color: #E67474;
}
.two {
    width: 200px;
    height: 200px;
    background-color: #96C143;
}
.one,
.two {
    float: left;
}
</style>
<body>
 	<div class="float">
		我孩子浮动了
		<div class="one">浮动1</div>
		<div class="two">浮动2</div>
	</div>   
</body>

3. 使用 alter 伪元素

定义一个样式,给他添加一个伪元素,然后设置到 子元素 浮动的 父元素上,和 第一种方法一样:

<style>
.float {
    width: 500px;
    background-color: pink;
}
.clearfix {
    *zoom: 1;
}
.clearfix::after {
    content: "";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
.one {
    width: 100px;
    height: 100px;
    background-color: #E67474;
}
.two {
    width: 200px;
    height: 200px;
    background-color: #96C143;
}
.one,
.two {
    float: left;
}
</style>

<body>
	<div class="float clearfix">
		我孩子浮动了
		<div class="one">浮动1</div>
		<div class="two">浮动2</div>
	</div>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值