2 回答
Background Info
The default width of the body
element is the html
width which is also the window width (or iframe
width in such a case). The default behavior of a block level element is that the scroll only accounts for the actual element (hence, it doesn't care about the right margin if there is nothing more to display on the right). This causes your right margin issue. (By the way, according to this article, the scroll bars are actually appearing on the html element, not the body.)
For Position: Absolute
By having #wrapper
with position: absolute
, the body
element ends up with zero height. This causes your bottom margin issue in this case.
A solution is to account for the margins like so (see fiddle):
body {
min-height: 320px;
min-width: 420px;
}
This assigns a minimum dimension to the body
equal to the width + margins and height + margins of the absolute element.
Now, I'm not sure what you expect to happen if you have right: 0
set, as forcing a left margin to "remain" just ends up causing, in my opinion, a premature scroll bar to activate. See this fiddle.
Regarding Position: Static
The default block level behavior can be changed by forcing a shrink-wrap like behavior on the body element using (see fiddle):
body { display: inline-block; }
Note: that body { float: left; }
did not give me the same shrink-wrap behavior (see fiddle).
The inline-block
element will account for the margin of its inner elements to determine its own width, which then allows the right margin to work.
The reason the display: inline-block;
solution does not work on the #wrapper
being position: absolute
is because it makes the body
have a zero width and height, since the absolute positioning takes that element out of flow and there is nothing left inside body
to give it dimension.
The above was currently only tested on IE9.
I'm afraid there's only one simple and quick solution, and that is to create a new div inside the wrapper div.
CSS
#wrapper {
background: black;
height: 300px;
margin: 10px;
position: absolute;
top: 0;
left: 0;
width: 400px;
}
#inwrapper {
background: green;
height: 290px;
margin: 5px auto;
position: relative;
width: 390px;
}
HTML:
<div id="wrapper">
<div id="inwrapper">
</div>
</div>
And there's your margin.