1

I have two variable-width elements that I'm trying to position the following way:

  1. If they fit next to each other on the screen or in their common container, I want them align to the opposite sides of it (i.e. the second one aligned to right).
  2. If they don't, I want them one above the other, but both aligned to the left.

Something as simple as:

<div class="container">
  <div style="display: inline-block;">
    I'm a variable width left element
  </div>
  <div style="display: inline-block; float:right;">
    I'm right-floating if there's space
  </div>
</div>

takes care of the first case, but obviously when the container is small enough for the second div to be rendered below the first one, it's still right-floating which is not what I want.

Is this even possible with pure CSS? I can't use media queries because of unknown/variable widths.

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
zuza
  • 135
  • 1
  • 5
  • CSS has a lot of holes (desirable layouts that cannot be expressed with pure CSS). It _might_ be possible if you float the first box left, (play with `display:block` as well) but I've found that a little Javascript is often needed. – Jim Garrison Dec 13 '15 at 22:46

1 Answers1

3

This layout and behavior is possible without media queries and pure CSS using flexbox.

HTML

<!-- horizontal alignment when two boxes fit -->
<div class="container">
    <div class="box box1"><span>1</span></div>
    <div class="box box2"><span>2</span></div>
</div>

<!-- vertical alignment when two boxes don't fit -->
<div class="container">
    <div class="box box3"><span>1</span></div>
    <div class="box box4"><span>2</span></div>
</div>

CSS

.container {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    width: 700px; /* for demo only; can be relative length, as well */
}

.box1 { width: 100px; }
.box2 { width: 150px; }
.box3 { width: 400px; }
.box4 { width: 500px; }

enter image description here

DEMO

NOTES:

  • When there is enough space to fit both variable-width elements on the same row, they are aligned at opposite ends of the container with justify-content: space-between.

  • When there is not enough space to fit both elements, they wrap with flex-wrap: wrap and align-left because the justify-content: space-between rule will left-align an element when it is alone on the row.


Note that flexbox is supported by all major browsers, except IE 8 & 9. Some recent browser versions, such as Safari 8 and IE10, require vendor prefixes. For a quick way to add all the prefixes you need, post your CSS in the left panel here: Autoprefixer.

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