Home > Back-end >  position div next to another div
position div next to another div

Time:04-24

how can I accomplish the following effect:

IMG

I have this:

<div id='div1'>
  text
  <div id='div2'>text</div>
</div>

#div1{
  text-align:center;
  background:blue;
  width:100px;
}

#div2{
  position: absolute;
  background:red;
  top:8px;
  left:108px;
}

But when the window is resized, div 2 moves relative to the window size

CodePudding user response:

Create a container with a flexbox (see: https://css-tricks.com/snippets/css/a-guide-to-flexbox/) and then position them that way. You could do it with positioning but that seems needlessly complicated for what you're trying to achieve and it'll create more problems as you resize the screen as you've discovered. Position is relative so as your screen size changes, so will your positioning. This method will give you more control over positioning elements if you want them in specific places and layouts.

.container {
  display: flex;
  flex-direction: row;
  border: 1px solid black;
  width: 200px;
}

#div1 {
  text-align: center;
  background: blue;
  width: 100px;
  height: 200px;
}

#div2 {
  background: red;
    margin-top: 50px;
  width: 100px;
  height: 100px;
}
  <div >
    <div id='div2'>text</div>
    <div id='div1'>text</div>
  </div>

  • Related