15

如何将包装元素中的两个元素向右浮动,在视觉和语义上保持元素的相同顺序?

<style>
.container { widht: 200px; height: 50px; background: #333; }
.container p { width: 50px; height: 50px; background: #f00; float: right; margin: 0; }
</style>
<div class="container">
    <p class="a">Simon</p>
    <p class="b">Says</p>
</div>

渲染时,这将使内部元素按照“Says Simon”的顺序出现,http://jsbin.com/eravan/1/edit

4

4 回答 4

15

您也可以在父元素上设置时使用display: inline-block;而不是。floattext-align: right;

http://jsbin.com/eravan/10/edit

于 2013-01-26T15:03:40.043 回答
10

常见的修复方法是:

添加辅助元素

<style>
.container { width: 200px; height: 50px; background: #333; }
.container p { width: 50px; height: 50px; background: #f00; float: left; margin: 0; }
.container .aux { float: right; }
</style>
<div class="container">
    <div class="aux">
        <p class="a">Simon</p>
        <p class="b">Says</p>
    </div>
</div>

http://jsbin.com/eravan/6/edit

这种方法的问题在于冗余的辅助元素本身。

混淆语义

<style>
.container { width: 200px; height: 50px; background: #333; }
.container p { width: 50px; height: 50px; background: #f00; float: right; margin: 0; }
</style>
<div class="container">
    <p class="b">Says</p>
    <p class="a">Simon</p>
</div>

http://jsbin.com/eravan/9/edit

这是最糟糕的解决方案,不幸的是,也是最常见的解决方案(下面的Ali Bassam 评论证明了这一点)。

这些都不是正确的答案。

于 2013-01-26T15:00:34.537 回答
2

flexbox 有很多可能性(包括视觉上的重新排序元素),所以您将采取的方法取决于周围的内容。但是 IE 直到版本 10 才支持它。

http://caniuse.com/#feat=flexbox

.container {
    width: 200px;
    height: 50px;
    background: #333;
    display: flex;
}

.container.a {
    justify-content: flex-end;
}

.container p {
    width: 50px;
    height: 50px;
    background: #f00;
    margin: 0;
}

.container.b .a {
    margin-left: auto;
}

<div class="container a">
    <p class="a">Simon</p>
    <p class="b">Says</p>
</div>

<hr />

<div class="container b">
    <p class="c">Let's Play</p>
    <p class="a">Simon</p>
    <p class="b">Says</p>
</div>

http://jsfiddle.net/6NWmt/(不包括前缀)

于 2013-01-26T16:26:59.397 回答
0

另一种方法可能是使两个类成为绝对并指定它们的位置?如果您的元素是固定大小的,这将相对简单。只是一个想法..

于 2013-01-26T15:17:43.583 回答