一. 关于display:inline-block
inline-block的特性:
1、使块在一行显示;
2、行内属性标签支持宽和高;
3、没有宽度的时候,宽度由内容撑开;
※※ 使用它会出现以下问题 ※※
1、代码换行会被解析(br);
2、ie6、ie7 不支持块属性标签的inline-block;
有什么办法可以解决以上问题???答案是使用浮动。
二. 浮动的原理
元素加了浮动,会脱离文档流 ,按照指定的一个方向移动直到碰到父级的边界或者另外一个浮动元素停止。
小贴士:文档流是文档中可显示对象在排列时所占用的位置。
设置浮动后,元素具有以下特性:
1、使块元素在一行显示;
2、使内嵌元素支持宽高;
3、不设置宽度的时候宽度由内容撑开;
4、脱离文档流;
float : left / right / none
三. 清浮动
为什么要清浮动?
因为浮动会对父元素和后面的元素有影响,当前面的元素设置为浮动后,它就脱离了文档流,后面的元素就会往上顶。
清浮动就是去除前面元素浮动对后面元素以及父元素的影响。
当父元素没有指定高度而它的子元素有浮动,这时这个父元素的高度不会自动增加(自适应)。
clear : left / right / both / none
清浮动的方法:
1、给父级也加浮动
问题:页面中所有父级都要加浮动。
<style>
.box{ width:300px;margin:0 auto;border:10px solid #000; float:left;}
.div{ width:200px;height:200px;background:red;float:left;}
/*
清浮动:
1.给父级也加浮动
*/
</style>
<div class="box">
<div class="div"></div>
</div>
2、给父级加display:inline-block
问题:margin左右居中失效
<style>
.box{ width:300px;margin:0 auto;border:10px solid #000; display:inline-block;}
.div{ width:200px;height:200px;background:red;float:left;}
/*
清浮动:
2.给父级加display:inline-block
*/
</style>
<div class="box">
<div class="div"></div>
</div>
3、在浮动元素下加<div class="clear"></div>
问题:IE6 最小高度19px;(解决后IE6下还有2px偏差)
<style>
.box{ width:300px;margin:0 auto;border:10px solid #000;}
.div{ width:200px;height:200px;background:red;float:left;}
.clear{ height:0px;font-size:0;clear:both;}
/*
清浮动:
3.在浮动元素下加<div class="clear"></div>
.clear{ height:0px;font-size:0;clear:both;}
*/
</style>
<div class="box">
<div class="div"></div>
<div class="clear"></div>
</div>
4、在浮动元素下加<br clear="all"/> == clear:both
问题:不符合工作中结构、样式、行为三者分离的要求。
<style>
.box{ width:300px;margin:0 auto;border:10px solid #000;}
.div{ width:200px;height:200px;background:red;float:left;}
/*
清浮动:
4.在浮动元素下加<br clear="all"/>
*/
</style>
<div class="box">
<div class="div"></div>
<br clear="all"/>
</div>
5、给浮动元素的父级加{zoom:1;}
:after{content:""; display:block;clear:both;}
<style>
.box{margin:0 auto;border:10px solid #000;}
.div{ width:200px;height:200px;background:red;float:left;}
.clear{zoom:1;} // 在ie67下触发haslayout
.clear:after{content:""; display:block;clear:both;} // 元素末尾追加内容
/*
清浮动:
5. 给浮动元素的父级加{zoom:1;}
:after{content:""; display:block;clear:both;}
*/
</style>
<div class="box clear">
<div class="div"></div>
</div>
**在IE6,7下浮动元素的父级有宽度就不用清浮动**6、父级加绝对定位
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#box1{border:30px solid red; position:absolute;}
#box2{ width:300px; height:300px; background:blue; float:left;}
</style>
</head>
<body>
<div id="box1">
<div id="box2"></div>
</div>
</body>
</html>
7、父级加固定定位
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#box1{border:30px solid red; position:fixed;}
#box2{ width:300px; height:300px; background:blue; float:left;}
</style>
</head>
<body>
<div id="box1">
<div id="box2"></div>
</div>
</body>
</html>