Tyler Graf
Tyler Graf

Reputation: 454

Flexbox - Horizontally Center 3 elements but align on center element

I'd like to use flexbox to center 3 elements together on a page. The middle element is ultimately the center of the page while the left and right elements can vary in width. Please refer to image below.

description of centering

I don't know if this is possible with flexbox. I'd just like it to be.

No real structural requirements other than I'd like to be able to align the elements vertically on a mobile device or as soon as the window width is too small for them to be aligned horizontally. mobile view of elements

Upvotes: 6

Views: 3913

Answers (1)

Paulie_D
Paulie_D

Reputation: 115061

OK...it took some tweaking and possibly involves more wrappers than you might be comfortable with but I think I've gotten close.

Basic principle

We need rows, each of which contains three colums for this. Each of those column divs holds a "content" div which recieves the actual content (and thus bg color).

Using flexbox we can tell the center column (and it's content div) to be a fixed width while each of the side divs is flexible.

The content divs inside the side columns are auto-width and are aligned as required using flex-end/start etc.

When the media query kicks in, the rows become columns instead and the previous 'column' divs become rows in that column.

.row {
  display: flex;
  margin-bottom: .5em;
}

.content {
  text-align: center;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 1em;
}

.col {
  flex: 1;
  display: flex;
}



.center {
  flex: 0 0 350px;
  display: flex;
  margin: 0 .5em;
}

.center .content {
  background: pink;
  flex: 1 1 100%;
}

.left {
  justify-content: flex-end;
}

.left .content {
  flex: 0 1 auto;
  background: blue;
}

.right .content {
  flex: 0 1 auto;
  background: green;
}

@media screen and (max-width:700px) {
  .row {
    flex-direction: column;
  }
  
  .col {
    flex: 1;
    justify-content: flex-end;
  }
  
 
  .center {
 margin: 0;
  }
}
<div class="container">
  <div class="row">
    <div class="col left">
      <div class="content">Lorem ipsum dolor sit amet.</div>
    </div>
    <div class="col center">
      <div class="content">Lorem </div>
    </div>
    <div class="col right">
      <div class="content">Lorem ipsum.</div>
    </div>
  </div>
    <div class="row">
    <div class="col left">
      <div class="content">Lorem ipsum dolor sit. Lorem ipsum.</div>
    </div>
    <div class="col center">
      <div class="content">Lorem ipsum dolor.</div>
    </div>
    <div class="col right">
      <div class="content">Lorem</div>
    </div>
  </div>
</div>

Codepen Demo

There's still some work to do depending on the break-point you want and exacly how the 'mobile' sized design is supposed to look...but I think I've made a fairly good start.

Upvotes: 6

Related Questions