-1

I have a div-container (colored blue) where I want to put 3 div-elements (colored red).

div-elements have to be vertically aligned (I just used margin-top: 10%; for that) and first one has to be left, second centered and third right in the same line. To achieve that I have made 3 ids #left, #center and #right.

However it all gets messed up when I put those ids in. First one is aligned allright, second one is centered but margin-top: 10%; doesn't affect it anymore and the third one is on the right side but in the new line.

I have tried putting display: inline-block; in my div-element class. This aligns right element correctly but messes up the center one.

Why is this happening and how do I solve this?

It is quite obvious that I have tried How to align 3 divs (left/center/right) inside another div? since I have used exact same ids, but the above mentioned solution doesn't work here and I have specifically asked why my margin-top: 10%; in .div-element doesn't affect center div

.div-container {
  width: 50%;
  height: 50%;
  background-color: blue;
}

.div-element {
  margin-top: 10%;
  width: 20%;
  height: 50%;
  background-color: red;
}

#center {
  margin: 0 auto;
}

#left {
  float: left;
}

#right {
  float: right;
}
<div class="div-container">
  <div class="div-element" id="left">Left</div>
  <div class="div-element" id="center">Center</div>
  <div class="div-element" id="right">Right</div>
</div>
cheshire
  • 1,109
  • 3
  • 15
  • 37

2 Answers2

2

I would suggest using flexbox for this:

.div-container {
  width: 50%;
  height: 50%;
  background-color: blue;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.div-element {
  margin-top: 10%;
  width: 20%;
  height: 50%;
  background-color: red;
}
<div class="div-container">
  <div class="div-element">Left</div>
  <div class="div-element">Center</div>
  <div class="div-element">Right</div>
</div>
philngo
  • 913
  • 7
  • 12
0

One of the easiest way for me to do this would be to use CSS grid to position the columns

 <style>
       .div-container {
      display:grid;
      grid-template-column: 3, 1fr;
       width: 50%;
      }
   </style> 
Barri
  • 44
  • 4