Flexbox - Horizontal center of 3 items, but aligned to center item

I would like to use flexbox to combine three items on a page. The middle element is the center of the page, and the left and right elements are in width. See image below.

alignment description

I don't know if this is possible with flexbox. I just wish it were.

No real structural requirements, other than that I would like to be able to align elements vertically on a mobile device, or as soon as the window width is too small, so that they are horizontally aligned. mobile view of elements

+3


source to share


1 answer


OK ... it took a few tweaks and there might have been more wrappers than you'd be comfortable with, but I think I've closed.

The basic principle

We need rows, each with three columns for this. Each of these column separators contains a "content" div that receives the actual content (and therefore the bg color).

By using flexbox

, we can give the center column (and its content div) a fixed width, while each of the side divs is flexible.

The content of the div inside the side columns is auto-width and is aligned as needed with flex-end/start

etc.



When the media query fires, the rows become columns instead, and the previous divs in the column 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>
      

Run codeHide result


Demo Codepen

There is still some work to do depending on the breakpoint you want and how the "mobile" size design should look ... but I think I made a good start.

+4


source







All Articles