css position with percent

不羁岁月 提交于 2019-12-04 03:57:39

The problem is that percent values in margin are always relative to width, not height. You can achieve this by using absolute positioning instead, and setting a "top" value on each row. Like this:

.row {
    position: absolute;
    width: 80%;
    background: red;
    height: 30%;
}

#z1 {
    top: 0%;
}

#z2 {
    top: 35%;
}

#z3 {
    top: 70%;
}

http://jsfiddle.net/ELPJM/8/

Razz

It's your margin: 5% 0; that makes the height change. I'm not sure what margin-top and -bottom measures its percentage from but its not from the same as the parent element height. Therefore you cant use it to count it towards 100% height.

try this instead:

<div id="zwrapper">
    <div id="z1" class="row"></div>
    <div class="spacing"></div>
    <div id="z2" class="row"></div>
    <div class="spacing"></div>
    <div id="z3" class="row"></div>
</div>

with the styling:

.spacing{ height: 5%; }

HTML

<div id="zwrapper">
    <div class="holder">
        <div id="z1" class="row"></div>
        <div id="z2" class="row"></div>
        <div id="z3" class="row"></div>
    </div>
</div>

CSS

html,body{height: 100%;}
#zwrapper{min-height: 100%;}
#zwrapper:after{
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    width: 1px;
}
#zwrapper.holder{
    display: inline-block;
    vertical-align: middle;
}

This should solve it

.row{
    position: relative;
    width: 80%;
    margin:0 auto;
    background: red;
    height: 30%;
}
#z2{
    margin: 5% auto;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!