0

HTML

<body>
  <div id='el1'>
   <div class='directChildren' style='width:50%;height:100px;float:left;margin-top:0'>
    ....
   </div>
  </div>
  <div id='el2'>
   <div class='directChildren' style='width:50%;height:100px;float:right;margin-top:20px'>
    ....
   </div>
  </div>
  <div style='clear:both'/>
</body>

JS

const topEl1 = document.getElementById("el1").getBoundingClientRect().top; // return 0 (only example)
const topEl2 = document.getElementById("el2").getBoundingClientRect().top; // return 20 (topEl1 + margin top of el2)

QUESTION: Both of divs (el1, el2) has same top coordinate but why getBoundingClientRect return different ?. This case also happen for margin-bottom.

1 Answer 1

1

Because the CSS is not properly defined. You are using float on inner element(.directChildren) instead of using it on #el1 and #el2 without properly clearing float behavior on parent elements. That is why the effect of margin-top is overflowing the parent's dimension.

It is much easier to achieve the correct result by using following HTML and CSS where I have used proper styling by using flex. You can also use float if you want.

<div class="container">
  <div id='el1'>
    <div class='directChildren' style='height:100px;margin-top:0'>
      ....
    </div>
  </div>
  <div id='el2'>
    <div class='directChildren' style='height:100px;margin-top:20px'>
      ....
    </div>
  </div>
</div>
.container {
  display: flex;
}
.container .directChildren {
  flex: 1;
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'am sory, the code has been edited, please review again. That was what i mean before.
@Kardinata Please don't change a question after it has been answered as this invalidates the answer. Ask a new follow-up question instead. I will roll back the question to its original version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.