Whatever Whatever - 2 years ago 54
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>


I want the
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
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
    on the
    s because I need vertical margins.

  • I can't use
    on the
    s because this reverses their order.

Answer Source

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;

li {
  margin-right: auto;

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download