HTML 浮动右元素顺序

如果我有三个向右浮动的元素,为什么顺序如下(参见 jsfiddle)元素1是右边的第一个元素,而元素3实际上是最后一个元素。

现在是秩序

[3] [2] [1]

但是元素在 html 中是按照这个顺序排列的

[1] [2] [3]

为什么?

Http://jsfiddle.net/a9ap7/

69152 次浏览

That 'inverted order' is the intended result.

You can dig around in the CSS Specification if you'd like, but your example renders as it ought to.

If you'd like them to display in the same order as the markup, float the .container right, its children left.

Updated jsfiddle

The first element moves to the right, stops when it hits the edge of the container and allows the next element to move up to its left.

The second element then does the same, except it stops when it hits the left edge of the first element.

… and so on.

Using float or any other css property has no effect on html source code.

Any element that follows the floated element will flow around the floated element on the other side.

If you float an image to the left, any text or other elements following it will flow around it to the right. And if you float an image to the right, any text or other elements following it will flow around it to the left.

If both elements set to float the same direction (in this case- right), the first one which appears in our HTML (not CSS!) be the one on the far side close to the edge.

float property starts it's analysis from the most right to most left.
ex:

<div class="block block-1"></div>
<div class="block block-2"></div>
<div class="block block-3"></div>

with this rule:

.block {
float: left;
}

block-3 gets aligned to the left, we have: block-3, block-1, block-2
block-2 gets aligned to the left, we have: block-2, block-3, block-1
block-1 gets aligned to the left, we have: block-1, block-2, block-3

with this rule:

.block {
float: right;
}

block-3 gets aligned to the right, we have: block-1, block-2, block-3
block-2 gets aligned to the right, we have: block-1, block-3, block-2
block-1 gets aligned to the right, we have: block-3, block-2, block-1

If you want them float:right in the right order: block-1, block-2, block-3
then you should swap them in markup

<div class="block block-3"></div>
<div class="block block-2"></div>
<div class="block block-1"></div>

UPDATE: Or wrap them all in a parent, and only float parent

This is because in your html, you have specified that [element 1] be displayed first aligned to the right. Hence this is exactly what the browser renders. When, in your html, you go on to display [element 2], floated to right, the browser does this BUT AFTER giving [element 1] priority of being displayed to the right as [element 1] came first in your HTML.

Hope this makes sense.