Home > front end >  CSS Display: inline-block but Stack Divs only if they overlap
CSS Display: inline-block but Stack Divs only if they overlap

Time:02-14

I have the following divs below:

.parent {
  padding: 10px;
  background: grey;
}

.child {
  background: green;
  display: block;
  position: relative;
  width: 50px;
}

.stacked {
  left: 0px;
}

.three {
  left: 200px;
}
<div >
  <div >div1</div>
  <div >div2</div>
  <div >div3</div>
</div>

This looks like the following: enter image description here

I would like divs 1 and 2 to stack as they do, but since div3 does not collide with the divs above, I'd like it to vertically aline with div 1.

If I switch display to inline or inline-block, it pushes div 2 to the right of div one. and the left values are not accurate to the parant. enter image description here

The left values of the divs will be dynamically generated so I cannot know if the divs are overlapping or not.

Is this possible?

CodePudding user response:

You can use the column-count property like so:

.parent {
  padding: 10px;
  background: grey;
  column-count: 2;
}

.child {
  background: green;
  display: block;
  width: 50px;
}
<div >
  <div >div1</div>
  <div >div2</div>
  <div >div3</div>
</div>

Or you can use flexbox to wrap vertically, like so:

.parent {
  padding: 10px;
  background: grey;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 50px;
}

.child {
  background: green;
  display: block;
  width: 50px;
}
<div >
  <div >div1</div>
  <div >div2</div>
  <div >div3</div>
</div>

CodePudding user response:

Try this : wrap div3 item in another div and give it a class property of flex-container.

.flex-container {
  align-content: flex-start;
}

Ensure the flex direction is horizontal.

CodePudding user response:

Use display: flex property for all three div to become one line.

.parent {
        padding: 10px;
        background: grey;
        display: flex;
    }

    .child {
        background: green;
        display: block;
        position: relative;
        width: 50px;
        margin: 0 5px;
        padding: 5px;
    }

    .stacked {
        left: 0px;
    }

    .three {
        left: 200px;
    }
<div >
    <div >div1</div>
    <div >div2</div>
    <div >div3</div>
</div>

  • Related