今天在看div布局的时候讲到了利用float属性来实现元素的浮动,一开始搞得不是很明白,现总结如下:
无论如何,div是一种块元素,每个元素铁定会占一行,无论当前行是否已经用完了,也就是所谓的“流”的概念
例如:
<div id="container">
<div id="b1">1号块</div>
<div id="b2">2号块</div>
<div id="b3">3号块</div>
<div id="b4">4号块</div>
</div>
样式:
div#container{
background-color: grey;
width: 100%;
height: 200px;
}
div#b1{
width: 50px;
height: 50px;
background-color: red;
}
div#b2{
width: 50px;
height: 50px;
background-color: aquamarine;
}
div#b3{
width: 50px;
height: 50px;
background-color: blueviolet;
}
div#b4{
width: 50px;
height: 50px;
background-color: yellow;
}
结果如下:
如果一个div块被设为浮动的话,它将脱离这个流,自主地去填充这个区域,去靠到最左边或者最右边
比如讲2号块设为向左浮动,为了醒目,将3号块的长度变长了
div#container{
margin: 0px;
background-color: grey;
width: 100%;
height: 500px;
}
div#b1{
width: 50px;
height: 50px;
background-color: red;
}
div#b2{
width: 50px;
height: 150px;
background-color: aquamarine;
float: left;
}
div#b3{
width: 50px;
height: 250px;
background-color: blueviolet;
}
div#b4{
width: 50px;
height: 50px;
background-color: yellow;
}
效果如下:
如果将连续的两个块设为浮动的话,他们都将和流中的上一个元素的下边沿对齐,并且靠后的那个浮动元素(假设两个浮动元素都是向左浮动的)会靠在前面那个元素的左边。如果空间不够,则会被挤向下一行。
比如:
div#container{
margin: 0px;
background-color: grey;
width: 100%;
height: 500px;
}
div#b1{
width: 50px;
height: 50px;
background-color: red;
}
div#b2{
width: 50px;
height: 150px;
background-color: aquamarine;
float: left;
}
div#b3{
width: 50px;
height: 250px;
background-color: blueviolet;
float: left;
}
div#b4{
width: 50px;
height: 250px;
background-color: yellow;
}
效果图如下(为了不被挡住,将4号块的长度伸长为250Px):
当然,也可以向右浮动。这样的话,排在前面的元素会更靠右,后面的元素会更靠左。
还有一点要注意,就是元素的id必须以英文字母开头,否则识别不到。