user3494047 user3494047 -4 years ago 130
CSS Question

How to align element with another element which is aligned with flex?

I have a row of two elements inside of a flex container which are centered using the CSS properties

-webkit-flex-flow: row wrap;
and
justify-content: space-around;
. Above this row I want to have a div with text which is vertically aligned with the left most div in the row.

Is it possible to do this using only CSS with the requirement that the elements keep their
display: flex;
property?

Here is my html:

<div class="flex-container">
<div class="info-box">

</div>
<div class="type-one">

</div>
<div class="type-one">

</div>
</div>


and here is the css:

.flex-container {
padding: 0;
margin: 0;

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;

-webkit-flex-flow: row wrap;
justify-content: space-around;
}

.type-one{
width: 45%;
height: 50px;
background: tomato;

text-align: left;

display: -webkit-box;
display: -moz-box;
display: -ms-flexbox;
display: -webkit-flex;
display: flex;

-webkit-flex-flow: row wrap;
justify-content: flex-start;
}
.info-box{
width: 100%;
height: 10px;
background: tomato;
margin-bottom: 3px;
}


Here is a fiddle example. You can see how the top row starts all the way from the left (since it has flex-start alignment), but I want it to start at the location where the leftmost element in the second row starts. Is this possible with the given requirements?

Edit: I realized that I can add a margin-left of 2.5% to the info-box or make its width 95%, but I would prefer a solution which is relative to the type-one elements so that if I change their width the info-box will automatically realign to them.

Answer Source

To have them align on the left edge, set the left/right margins of the parent element to match wherever you want the columns in the middle to start. Change justify-content from space-around to space-between so that the left spacing of the middle columns won't change, and use the width of those elements to create space between them.

.flex-container {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    
    padding: 0;
    margin: 0;
    width: 95%;
    margin: auto;
}

.type-one{
  height: 50px;
  background: tomato;
  text-align: left;
  width: 47.5%;
}

.type-two{
  width: 100%;
  margin-top: 10px;
  font-size: 15px;
  text-align: center;
  height: 20px;
  background: tomato;
}

.info-box{
  width: 100%;
  height: 10px;
  background: tomato;
  margin-bottom: 3px;
}
<div class="flex-container">
  <div class="info-box"></div>
  <div class="type-one"></div><div class="type-one"></div>
  <div class="type-two"></div>
</div>

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