Whatever Whatever - 7 months ago 9
HTML Question

Forcing right alignment with floated elements not possible when word wrapping

<div id="wrap" style="width:300px">
<ul style="float:right">
<li style="float:left">first</li>
<li style="float:left">second</li>
<li style="float:left">third</li>
<li style="float:left">and the fourth is longer than the others</li>
</ul>
</div>


https://jsfiddle.net/xLq1hfby/

I want the
<li>
s to align to the right like this:

[first] [second] [third]
[and the fourth is longer than the others]


However, since the last element causes a word wrap, it just looks like this:

[first] [second] [third]
[and the fourth is longer than the others]


When the last
<li>
is removed, they align like I want them to, like this:

[first] [second] [third]


How can I get them to align to the right even when word wrapping?

Please keep in mind:


  • I can't use
    display:inline-block
    on the
    <li>
    s because I need vertical margins.

  • I can't use
    float:right
    on the
    <li>
    s because this reverses their order.


Answer

You can use flexbox with the following settings (note: no float, 'justify-content: flex-end;' aligns the items to the right.):

ul {
  display: flex;
  justify-content: flex-end;
  flex-wrap: wrap;
  list-style-type:none;
  margin:0;
  padding:0;
}

li {
  margin-right: auto;
  background:red;
  color:#fff;
  margin:4px;
}

Here is a fork of your fiddle: https://jsfiddle.net/0o93dvrp/