How to line up consecutive divs left and right?

Issue

Hello I’m not too good with css/floats/blocks etc.

I have this sort of setup

         <div class="blue">1</div>
         <div class="red">2</div>
         <div class="blue">3</div>
         <div class="red">4</div>
         <div class="blue">5</div>
         <div class="red">6</div>

I want to style it so 1 and 2 are on the same line (floated left and right), then 3 and 4 are on the same line (floated left and right) and so on and so forth.

Currently these elements are created in a loop. I have tried all sorts of methods to get the elements to line up how I want to no avail.

Solution

I think you want to make them two per row correct?

You can add a flex property to the parent container. Set the flex-wrap to wrap, then add a 50% width on your child elements (taking into account any inherited margin or padding effecting the layouts width to not overflow the flex-wrap), then justify-content to space-between, this will force the elements to their respective sides or a better way to put it is; place the "left over" space the children on that row are not taking up, in the middle of the two elements.

* { /* set box-sizing on all elements to border-box */
  box-sizing: border-box;
}

body { /* remove any margin or padding from the body */
  margin: 0;
  padding: 0;
}

#cont { /* add display flex, flex-wrap and justify-content to space between */
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

#cont>div { /* Set your child divs to a percentage that will only give you two per row
the flex-wrap will push elements down */
  width: 50%;
}

.blue { 
  background-color: lightblue;
  border: 1px solid darkblue;
}

.red {
  background-color: pink;
  border: 1px solid darkred;
  text-align: right; /* remove if you want standard left side text-alignment on red elements */
}
<div id="cont">
  <div class="blue">1</div>
  <div class="red">2</div>
  <div class="blue">3</div>
  <div class="red">4</div>
  <div class="blue">5</div>
  <div class="red">6</div>
</div>

If this is not what you were looking for let me know and I can edit or remove this answer.

Answered By – dale landry

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.