问题描述:

After a couple of waisted hours I've managed to find a solution to my problem, so the question is not "how to", but "why it works like that". Here's my stripped down example:

<div id="header">

<div id="header-element">header</div>

</div>

<div id="footer">footer</div>​

CSS:

#header {

width: 100%;

position: relative;

padding-bottom: 5%;

}

#header-element {

position:absolute;

bottom: 0;

}

#footer {

position: relative;

margin-top: 5%;

}​

And jsFiddle - http://jsfiddle.net/H7jwm/3/.

My problem was how to position those relatively positioned elements using percentage, first one some % off the top of the document, and the second one from the first one. I've accomplished that by giving padding-bottom to the first one, and margin-top to the second one, but I've got to the solution with a brute force - trying out every remotely logical solution. Now, if you remove the padding, margin-top of the second element becomes margin between that element and the top of the document, not the first element, and that first element "takes" rest of the space to the top.

The question is why that padding works like that? Or, to rephrase it, how does padding work with relative positioning?

网友答案:

Actually, you are mixing positions. Your #header has a height of zero. That's right, zero like in nothing, because it has no relative content. #header-element is absolutely positioned and because #header has a height of 0 it happens to be exactly in the padding-bottom space.

So, if you remove the padding-bottom from #header, the #footer moves up, starting right at the top of the document. Because of the margin-top, there's some space between the document top border and the word 'footer'.

But you still have that absolutely positioned #header-element, which will now be right in that margin-top space.

相关阅读:
Top