1

I would like to align two spans inside a container in a very peculiar way. One span should be left justified the other right justified, like this:

+---------------------+
|XXXXXXXXX   YYYYYYYYY|
+---------------------+

but when it comes to an overlap, the right aligned text should be placed in an extra row. Like this:

+--------------+
|XXXXXXXX      |
|       YYYYYYY|
+--------------+

The following code however aligns the second span to the left.

div {
  width: 40%; /* force narrow div to start with */
  display: flex; justify-content: space-between; flex-wrap: wrap;
}

<div>
  <span>left align some text</span>
  <span>right align some other text</span>
</div>
+-----------------------------+ /* yay */
|XXXXXXXXXXXXXX     YYYYYYYYYY|
+-----------------------------+

+--------------------+ /* nope */
|XXXXXXXXXXXXXX      |
|YYYYYYYYYY          |
+--------------------+

Leaving out flex wrap:

+--------------------+
|XXXXXXX       YYYYYY|
|XXXX            YYYY|
+--------------------+

I also tried

  • Using float+clear but this resulted in a zero height container
  • position: absolute; right: 0px which did not work relative to the container!

Is there a way to solve this without explicitly going though all my containers and computing everything via javascript?

1 Answers1

0

Instead of justify-content use auto margins.

div {
  display: flex;
  flex-wrap: wrap;
  width: 40%;
}

span:last-child {
  margin-left: auto;
}
<div>
  <span>left align some text</span>
  <span>right align some other text</span>
</div>

jsFiddle demo

Understanding flex auto margins.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701