How to float two elements to the right maintaining the same order visually and semantically?

China☆狼群 提交于 2019-12-03 16:32:33

问题


How to float two elements within a wrapper element to the right keeping the same order of the elements visually and semantically?

<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>

When rendered, this will make the inner elements appear in the order of "Says Simon", http://jsbin.com/eravan/1/edit.


回答1:


You can also use display: inline-block; instead of float while setting text-align: right; on the parent element.

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




回答2:


The common fixes are:

Adding auxiliary element

<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

The problem with this approach is the redundant auxiliary element itself.

Messing with the semantics

<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

This is the worst solution and, unfortunately, the most common as well (Ali Bassam comment directly below proves it).

Neither of these is the correct answer.




回答3:


There are lots of possibilities here with flexbox (including visually reordering elements), so the approach you would take depends on the surrounding content. However IE doesn't support it until version 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/ (prefixes not included)




回答4:


Another way to do this might be to make the two classes absolute and specify their location? If your elements are fixed size this would be relatively simple. Just a thought..



来源:https://stackoverflow.com/questions/14538106/how-to-float-two-elements-to-the-right-maintaining-the-same-order-visually-and-s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!