Css 基础案例 (2) —— 清除float浮动,解决float产生的副作用

3 篇文章 0 订阅
2 篇文章 0 订阅

CSS中的定位机制

  • 标准流
  • 定位
  • 浮动

float浮动的原因

float浮动的原因就是使浮动的元素脱离标准流,浮动的元素不占有原空间。

float浮动的副作用

理想效果:
这里写图片描述
float浮动的子元素会脱离标准流,父元素中就会没有东西撑开,会引起父元素塌陷或者其他元素异位。

<head>
    <title>清除浮动的测试</title>
    <meta charset="utf-8">
    <style>
        *{margin:0;padding: 0;}

        .box{
            width: 300px;
            height: auto;
            background-color: #000;
        }
        .subbox1{
            width: 200px;
            height: 50px;
            float: left;
            background-color: red;
        }
        .subbox2{
            width: 100px;
            height: 20px;
            float: right;
            background-color: yellow;
        }
        .subbox3{
            width: 100px;
            height: 60px;
            float: right;
            background-color: blue;
        }
        .footer{
            width: 100%;
            height: 60px;
            background-color: #CCC;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="box">
        <div class="subbox1"></div>
        <div class="subbox2"></div>
        <div class="subbox3"></div>
    </div>
    <div class="footer">footer</div>
</body>

现实效果:
这里写图片描述

解决float浮动的副作用

有4种方法

  • 给父元素添加高度
  • 使用clear清除内部和外部浮动
  • 给父元素添加overflow属性并结合zoom:1使用
  • 给父元素添加浮动

1.给父元素添加高度

.box{
        width: 300px;
        height: 80px;
        background-color: #000;
    }


2.使用clear清除内部和外部浮动

(1)在塌陷的父元素中添加CSS带有clear属性的div(或其他元素)

...
    .clear{
        clear: both; //清除左右浮动
    }
    </style>
</head>
<body>
    <div class="box">
        <div class="subbox1"></div>
        <div class="subbox2"></div>
        <div class="subbox3"></div>
        <div class="clear"></div>
    </div>
    <div class="footer">footer</div>
</body>


(2)给塌陷的父元素添加clear等相关css属性

..
        .clearfix:after{ //必须是伪类
            clear: both;
            content: ' ';
            height: 0;
            line-height: 0;
            display: block;
        }
    </style>
</head>
<body>
    <div class="box clearfix">
        <div class="subbox1"></div>
        <div class="subbox2"></div>
        <div class="subbox3"></div>
    </div>
    <div class="footer">footer</div>
</body>

以上的两种方法都可以实现:
这里写图片描述

3.给父元素添加overflow属性并结合zoom:1使用

字面意思

4.给父元素添加浮动

字面意思

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值