Issue
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 class="div-1">
<p>div1</p>
</div>
<div class="div-2">
<p>div1</p>
</div>
Solution
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 class="div-1 div--simple">
<p>div1 top gap depends on container width</p>
</div>
<div class="div-2 div--simple">
<p>div2 top gap depends on container width</p>
</div>
<hr />
<div class="div-1 div--pseudo">
<p>div1 with using pseudo gap</p>
</div>
<div class="div-2 div--pseudo">
<p>div2 with using pseudo gap</p>
</div>
<hr />
<div class="div-1 div--hv">
<p>div1 with using VH</p>
</div>
<div class="div-2 div--hv">
<p>div2 with using VH</p>
</div>
Answered By - Yaroslav Trach
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.