css float属性介绍 应用场景及优缺点
背景介绍
最近被问到一个float问题,应该公司的业务都是比较传统的管理系统,页面的布局就比较简单,所以float也只用在一些简单的场景,由于感觉自己对这一块研究的比较浅。最近也一直在写node开发,感觉前端的一些知识已经有些生疏,就决定仔细学一下,以下就是我学习的内容。
float的历史
在雅虎的页面还是这个样子的时候,float已经出现,出现的最初目的是为了文字环绕效果,而不是文字一行,图片一行的。

包裹与破坏
包裹的三个特征: 收缩 坚挺 隔绝(块级格式化上下文)
具有包裹属性的其他css属性:
-
display: inline-block/table-cell
-
position: absolute/fixed
-
overflow:hidden/scroll
破坏:当设置float属性,父元素的高度塌陷,类似的有:
-
列表项display: none;
-
position:absolute/fixed/sticky
所以浮动就是天使的魔鬼
造成这种结果的原因是,设计者初衷旧是为了实现文字环绕的效果,所以就利用破坏的这种方式,让设置float属性的标签的父元素的高度塌陷,然后让后面的元素补充标签留下来的空间
![]()
清除浮动
方法1: 底部插入:clear:both;
方法2: BFC
ie8+(.clearfix;after{content:'';display:block;height:0;overflow:hodden;clear:both)
ie8-(*zoom:1)
浮动对浮动元素的影响
1.元素block化
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>浮动去空格</title>
<style>
button { margin: 0; }
p { clear: both; }
</style>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<p><input type="button" id="trigger" value="点击按钮浮动"></p>
<script>
var trigger = document.getElementById("trigger"),
buttons = document.getElementsByTagName("button");
var length = buttons.length;
if (trigger && length > 0) {
trigger.onclick = function() {
for (var index = 0; index < length; index += 1) {
buttons[index].style["cssFloat" in trigger.style? "cssFloat": "styleFloat"] = "left";
}
};
}
</script>
</body>
</html>
2.破坏性造成的精密排列特性(去空格化)
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>浮动与display:block化</title>
<style>
.ovh { overflow: hidden; }
.red { color: #cd0000; }
[hidden] { display: none; }
</style>
</head>
<body>
<p id="first">这是一个没有设置<code>float</code>属性的按钮:</p>
<p class="ovh"><input type="button" id="btnShow" value="点击我显示display属性值"></p>
<p hidden="">此时,按钮的display属性值是:<span id="result" class="red"></span></p>
<p>点击下面的按钮让上面的按钮添加<code>float: left</code>的声明:</p>
<p><input type="button" id="btnAdd" value="上面的按钮添加float:left"></p>
<script>
var btnShow = document.getElementById("btnShow"),
btnAdd = document.getElementById("btnAdd"),
result = document.getElementById("result"),
first = document.getElementById("first");
if (btnShow && btnAdd && result) {
btnShow.onclick = function() {
// 获得该按钮的display值
var display = this.currentStyle? this.currentStyle.display: window.getComputedStyle(this, null).display;
// 显示结果
result.innerHTML = display;
result.parentNode.removeAttribute("hidden");
// repain fix IE7/IE8 bug
document.body.className = "any";
};
// 设置浮动按钮的点击事件
btnAdd.onclick = function() {
btnShow.style["cssFloat" in this.style? "cssFloat": "styleFloat"] = "left";
// 文字描述的变化
this.value = "上面的按钮已经设置了float:left";
btnShow.value = "再次点击我确认display属性值";
first.innerHTML = first.innerHTML.replace("没有", '<del>没有</del>');
// 结果隐藏
result.parentNode.setAttribute("hidden", "");
// 按钮禁用
this.setAttribute("disabled", "");
};
}
</script>
</body>
</html>

浙公网安备 33010602011771号