问题
I have a main container div, and I'd like it to be margined from the top of the screen exactly, for example, 10%
of the screen width. This way I won't have problems with non-uniform screen sizes etc..
I already found a dirty workaround which is putting a 1px by 1px
image of the color of the background, right before the div, and then style it to have 10%
of the width of the screen. But this looks quite dirty, doesn't it? Is there any better solution?
回答1:
The solution I find very elegant is to insert the page in a table, beginning right after the body, and terminating right before it.
You'd have this:
<html>
<head><title>...</title></head>
<body>
<table id="content"><tr><td>
Your whole page comes here...
</td></tr></table>
</body>
</html>
Now simply decide the size of the page, using the style:
#content {
width: 850px;
margin-left: auto;
margin-right: auto;
}
回答2:
Same solution as Rubens without using tables. I've also placed some code to deal with the top margin you were asking about but using padding instead.
<html>
<head>
<title>...</title></head>
<body>
<div id="content">
Your whole page comes here...
</div>
</body>
</html>
* {
padding:0;
margin:0;
}
html, body {
height:100%;
}
body {
padding:10% 0 0;
}
#content {
width: 850px; // replace with your desired width
margin:0 auto;
}
来源:https://stackoverflow.com/questions/14022063/padding-of-a-certain-percentage-of-screen-width