关于CSS的clear:both的疑问

查看:75
本文介绍了关于CSS的clear:both的疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

在实现圣杯布局的时候遇到了一个问题,使用传统方式实现圣杯布局,在设置中间的三个模块都向左浮动之后,设置.main模块宽度为100%以使它独自占据一行。这时候我想到可不可以给.main设置clear:both属性它周围不存在浮动元素达到同样的效果,发现不起作用,代码如下:

//HTML部分
<body>
   <div class="header">header</div>
      <div class="container">
        <div class="main">main</div>
        <div class="left">left</div>
        <div class="right">right</div>
      </div>
<div class="footer">footer</div>
</body>

//CSS部分代码
*{
  margin: 0;
  padding: 0;
}
body
{
  min-width: 700px;
}
.header,.footer{
   border: 1px solid #333;
   background-color:white;
   text-align: center;
}
.left,.main,.right{
   min-height: 130px;
}
.container{
  overflow:hidden;
  border:2px solid blue;
}
.left{
   width:200px;
   background:yellow;
}
.right{
   width:220px;
   background:pink;
}
.main{
   width:100%; //如果设置clear:both;的话不起作用
   background-color:blue;
}

.left,.main,.right {
  float:left;
}

.footer {
  clear:both;
}

希望得到大家的解答。

解决方案

这是因为让 .main float 起来后,有两个特性:

  1. 不指定宽度的话就会按 shrink-to-fit 计算,即尽可能缩小。

  2. 宣布了新的 BFC,所以 clear 对其它两个 float 不起作用。

所以只需要取消 .main 的 float 即可,宽度会自动恢复为 100%。也不需要 clear ,因为后面的 float 是从 .main 下方开始计算。

这篇关于关于CSS的clear:both的疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆