说到元素的浮动,首先要明确一个概念就是包含块(containing block)。
所谓浮动元素的包含块,就是其最近的块级祖先元素。我们后面会举例来说明。
这里关于浮动的问题,主要有以下几点:
- 1、浮动元素的外边界不能超过其包含块的内边界。
- 2、浮动元素的外边界是另一浮动元素的外边界。
- 3、浮动元素的顶端不能比之前出现的浮动元素的顶端更高。
- 4、浮动元素顶端不超过当前行。
- 5、clear属性。
1、浮动元素的外边界不能超过其包含块的内边界。
我们看以下代码:
<div class="col-md-6" id="outerBlock">
<img src="images/test1.jpg" style="float:right" alt="plane" id="image1"/>
<p id="p1">Came a time remembered well,
When the strong young man of the rising sun
Heard the tolling of the great black bell.
One day in the Year of the Fox,
When the bell began to ring,
It meant the time had come for one to go
To the temple of the king.
There in the middle of the circle he stands,
Searching, seeking.
With just one touch of his trembling hand,
The answer will be found.
Daylight waits while the old man sings,
"Heaven help me!"
And then like the rush of a thousand wings,
It shines upon the One.
And the day has just begun.
One day in the Year of the Fox
Came a time remembered well,
WheOne day, in the Year of the Fox
Came a time remembered well,
When the strong young man of the rising sun
Heard the tolling of the great black bell.
One day in the Year of the Fox,
When the bell began to ring,
It meant the time had come for one to go
To the temple of the king.
There in the middle of the circle he stands,
Searching, seeking.
With just one touch of his trembling hand,
The answer will be found.
Daylight waits while the old man sings,
"Heaven help me!"
And then like the rush of a thousand wings,
It shines upon the One.
And the day has just begun. </p>
</div>
这段代码看第来比较长,实际上只有3个元素,最外层的div#outerBlock
以及其中包含的img#image1
和p#p1
。
注意代码第2行,我们让img#image1
元素向右浮动,此时,该img元素的包含块就为div#outerBlock
,也就是最外层的div块。
这段代码会呈现什么效果呢?为了更加清晰地说明问题,我们这里分别给div#outerBlock
以及p#p1
加上边框以及内边距:
div#outerBlock {
border: 1px dotted;
padding: 3em;
}
p#p1 {
border: 1px solid;
padding: 3em;
}
效果如下:
这里我们可以清楚地看到div#outerBlock
、img#image1
以及p#p1
三者的位置关系。
div#outerBlock
是img元素的包含块,img元素的外边界不得超过其包含块的内边界。由于div#outerBlock
元素增加了内边距padding=3em,故img元素的最右侧以及最上侧为虚线内3em。
如果我们给img元素加上2em的外边距,可以预料到img元素右侧及上侧将会为虚线内5em。如下:
img#image1 {
margin: 2em;
}
虽然看起来img元素很像包含在实线围起来的p元素中,事实上它的位置时依据它的包含块——虚线确定的,只是给img元素增加了2em的外边距,根据浮动元素外边界不超过其包含块内边界的原则,图像的边界将距离虚线5em。
接下来,我们做一些改变,将img元素放到p#p1
中去,如下:
<div class="col-md-6" id="outerBlock">
<p id="p1">Came a time remembered well,
When the strong young man of the rising sun
Heard the tolling of the great black bell.
One day in the Year of the Fox,
When the bell began