Home > OS >  How to get the distance in pixels between two margins in HTML/CSS?
How to get the distance in pixels between two margins in HTML/CSS?

Time:07-01

HTML

<div class = "container">
<p> class = "A"> One </p>
<p> class = "B"> Two </p>
</div>

CSS

.A{ margin-bottom: 40px;}
.B{margin-top: 10px;}
.container{height: 50px;}

I want to know how I can calculate to get the distance in pixels between .A and .B Thank You

Example

CodePudding user response:

Your HTML is invalid, so the styles are likely not applying.

You are closing the <p> tags before you apply the classname, you are also placing spaces around the = in the classname declaration. Both of these things are invalid.

Your HTML should look like this, when properly formatted

<div >
  <p > One </p>
  <p > Two </p>
</div>

As for the size, you are dealing with something called margin collapsing.

The margin between the two when this occurs will become equal to whichever margin was largest. In this case, 40px.

p{
  position: relative;
  background-color: red;
}

.measurement{
  position: absolute;
  height: 40px;
  color: white;
  background-color: blue;
  transform: translateY(-100%);
}

.A{ margin-bottom: 40px;}
.B{margin-top: 10px;}
.container{height: 10px;}
<div >
  <p > One 
    <div >40px</div>
  </p>
  <p > Two </p>
</div>

CodePudding user response:

JS Solution if you need dynamic calculations on, for instance, window resize.

You can pass DOM elements into the function as well.

 const getDistance = () => {
   const containerWidth = document.querySelector("#container").getBoundingClientRect().width;
   const A_width = document.querySelector("#A").getBoundingClientRect().width;
   const B_width = document.querySelector("#B").getBoundingClientRect().width;

   return containerWidth - (A_width   B_width);
   
 }
  • Related