温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

css清除浮动float的方法有哪些

发布时间:2021-04-13 12:23:21 来源:亿速云 阅读:250 作者:小新 栏目:web开发

这篇文章主要介绍css清除浮动float的方法有哪些,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

css清除浮动float的三种方法:1、在父元素结尾添加一个具体“clear: both;”样式的新元素。2、给父级div元素添加“overflow:auto;”样式;3、使用伪元素“:after”,给浮动元素的父元素清除浮动。

一、浮动的定义

使元素脱离文档流,按照指定方向发生移动,遇到父级边界或者相邻的浮动元素停了下来。

ps:文档流:文档流是文档中可显示对象在排列时所占用的位置 。

语法

float常跟属性值left、right、none

float:none 不使用浮动

float:left 靠左浮动

float:right 靠右浮动

二、浮动的用途

可设置文字环绕或使元素宽度由内容填充(类似Inline-block)。使用浮动需要注意的是如果浮动的元素高度比父级容器还高,那么需要设置父级容器的overflow属性为auto,使其自动撑满。

三、浮动用法

分析HTML结构:

<div class="box">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
  </div>

分析CSS代码样式:

.box {
      border: 1px solid #ccc;
      background: #fc9;
      color: #fff;
      margin: 50px auto;
      padding: 50px;
    }
    .div1 {
      width: 100px;
      height: 100px;
      background: darkblue;
      float: left;
    }
    .div2 {
      width: 100px;
      height: 100px;
      background: darkgoldenrod;
      float: left;
    }
    .div3 {
      width: 100px;
      height: 100px;
      background: darkgreen;
      float: left;
    }

css清除浮动float的方法有哪些

四、清除浮动

方法一:添加新元素,应用clear:both;

HTML:

<div class="box">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
    <div class="clear"></div>
  </div>

CSS:

.clear {
      clear: both;
      height: 0;
      line-height: 0;
      font-size: 0
    }

css清除浮动float的方法有哪些

一切恢复作用啦。

方法二:父级div定义overflow:auto;

HTML:

<div class="box">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
  </div>

CSS:

.box {
      border: 1px solid #ccc;
      background: #fc9;
      color: #fff;
      margin: 50px auto;
      padding: 50px;
      overflow: auto; 
      zoom: 1; /*zoom: 1; 是在处理兼容性问题 */
    }

结果:也是实现了。

方法三:在父级样式添加伪元素:after或者:before(推荐)

HTML:

<div class="box">
    <div class="div1">1</div>
    <div class="div2">2</div>
    <div class="div3">3</div>
  </div>

CSS:

.box {
      border: 1px solid #ccc;
      background: #fc9;
      color: #fff;
      margin: 50px auto;
      padding: 50px;
    }
.box:after{
      content: '';
      display: block;
      clear: both;
}

结果:当然不用说啦

css清除浮动float的方法有哪些

以上是“css清除浮动float的方法有哪些”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI