Home > Net >  How to line up consecutive divs left and right?
How to line up consecutive divs left and right?

Time:05-26

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

I have this sort of setup

         <div >1</div>
         <div >2</div>
         <div >3</div>
         <div >4</div>
         <div >5</div>
         <div >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.

CodePudding user response:

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 >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
</div>

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

  • Related