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