How to set the margin or padding as percentage of height of parent container?
I had been racking my brains over creating a vertical alignment in css using the following
.base{
background-color:green;
width:200px;
height:200px;
overflow:auto;
position:relative;
}
.vert-align{
padding-top:50%;
height:50%;
}
and used the following div structure.
<div class="base">
<div class="vert-align">
Content Here
</div>
</div>
While this seemed to work for this case, i was surprised that when i increased or decreased the width of my base div, the vertical alignment would snap. I was expecting that when I set the padding-top property, it would take the padding as a percentage of the height of the parent container, which is base in our case, but the above value of 50 percent is calculated as a percentage of the width. :(
Is there a way to set the padding and/or margin as a percentage of the height, without resorting to using JavaScript?
I also had this problem (+1). I'm seriously annoyed by it, it is stupid to have to do this.
The fix is that yes, vertical padding and margin are relative to width, but top
and bottom
aren't.
So just place a div inside another, and in the inner div, use something like top:50%
(remember position
matters if it still doesn't work)
Here are two options to emulate the needed behavior. Not a general solution, but may help in some cases. The vertical spacing here is calculated on the basis of the size of the outer element, not its parent, but this size itself can be relative to the parent and this way the spacing will be relative too.
<div id="outer">
<div id="inner">
content
</div>
</div>
First option: use pseudo-elements, here vertical and horizontal spacing are relative to the outer. Demo
#outer::before, #outer::after {
display: block;
content: "";
height: 10%;
}
#inner {
height: 80%;
margin-left: 10%;
margin-right: 10%;
}
Moving the horizontal spacing to the outer element makes it relative to the parent of the outer. Demo
#outer {
padding-left: 10%;
padding-right: 10%;
}
Second option: use absolute positioning. Demo
#outer {
position: relative;
}
#inner {
position: absolute;
left: 10%;
right: 10%;
top: 10%;
bottom: 10%;
}
对一个稍微不同的问题的答案:您可以使用vh
单位将元素填充到视口的中心:
.centerme {
margin-top: 50vh;
background: red;
}
<div class="centerme">middle</div>
链接地址: http://www.djcxy.com/p/13256.html
上一篇: 同一宽度的3个柔性箱项目的水平居中