Home > other >  Why is "margin-top:10%" pushing more than 10% of its parent div?
Why is "margin-top:10%" pushing more than 10% of its parent div?

Time:05-26

In my div-1 the height is 300px, but when I try to add margin to <p> inside of it, well it works pretty fine with px but with percentage it pushes more than 10% of its parent div.

* {
  box-sizing : border-box;
  margin     : 0; 
  }
.div-1 {
  border     : 2px solid yellow;
  background : rgb(15, 15, 145);
  color      : white;
  height     : 300px;
  }
.div-2 {
  border     : 2px solid rgb(218, 20, 208);
  background : rgb(53, 88, 13);
  color      : white;
  height     : 300px;
  }
.div-1 p {
  background : coral;
  padding    : 20px;
  width      : 20%;
  margin     : auto;
  margin-top : 10%;
  }
<div >
  <p>div1</p>
</div>
<div >
  <p>div1</p>
</div>

CodePudding user response:

When you defining margin in percentages, it's refer to the width of the containing block, try to use vh instead of %, or use another solution, if it's not suit your project; Other way is to using pseudo elements; See differences in Code Snippet:

* {
  box-sizing: border-box;
  margin: 0;
}

.div-1,
.div-2 {
  height: 300px;
  color: white;

}

.div-1 {
  border: 2px solid yellow;
  background: rgb(15, 15, 145);
}

.div-2 {
  border: 2px solid rgb(218, 20, 208);
  background: rgb(53, 88, 13);
  width: 70%;
}

.div-1.div--pseudo:before,
.div-2.div--pseudo:before {
  content: '';
  display: block;
  width: 100%;
  height: 10%;
  background: rgba(255, 255, 255, .2);
}


.div-1 p,
.div-2 p {
  background: coral;
  padding: 20px;
  width: 20%;
  margin-left: auto;
  margin-right: auto;
}

.div-1.div--simple p,
.div-2.div--simple p {
  margin-top: 10%;
}

.div-1.div--hv p,
.div-2.div--hv p {
  margin-top: 5vh;
}
<div >
  <p>div1 top gap depends on container width</p>
</div>

<div >
  <p>div2 top gap depends on container width</p>
</div>


<hr />

<div >
  <p>div1 with using pseudo gap</p>
</div>

<div >
  <p>div2 with using pseudo gap</p>
</div>

<hr />

<div >
  <p>div1 with using VH</p>
</div>

<div >
  <p>div2 with using VH</p>
</div>

CodePudding user response:

You can use css vars:

:root {
  --h300     : 300px;
  }
* {
  box-sizing : border-box;
  margin     : 0; 
  }
.div-1 {
  border     : 2px solid yellow;
  background : #0f0f91;
  color      : white;
  height     : var(--h300);
  }
.div-2 {
  border     : 2px solid #da14d0;
  background : #35580d;
  color      : white;
  height     : var(--h300);
  }
.div-1 p {
  background : coral;
  padding    : 20px;
  width      : 20%;
  margin     : auto;
  margin-top : calc(var(--h300) / 10);
  }
<div >
  <p>div1</p>
</div>
<div >
  <p>div2</p>
</div>

  • Related