我可以得到一个100%高度的div,像这样:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>T5</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" type="text/css"
href="http://yui.yahooapis.com/3.0.0/build/cssreset/reset-min.css">
</link>
<style type="text/css">
* { padding: 0; margin: 0; }
html, body { height: 100%; }
body {
font-family: "lucida sans", verdana, arial, helvetica, sans-serif;
font-size: 75%;
}
h1 { font-weight: bold; font-size: 1.4em; padding: 10px 10px 0;}
p { padding: 0 10px 1em; }
#container {
min-height: 100%;
background-color: #DDD;
border-left: 2px solid #666;
border-right: 2px solid #666;
width: 280px;
margin: 0 auto;
}
* html #container { height: 100%; }
</style>
</head>
<body>
<div id="container">
<h1>100% Height Div</h1>
<p>Lorem ipsum ...</p>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
它看起来像这样:
替代文字http://i41.tinypic.com/1j1do8.jpg
当我说"100%高度"时 - 我的意思是它保持全高,无论div中有多少内容,无论窗口如何调整大小.
但是有可能得到一个高度"几乎100%"高度的div?如果我想要顶部和底部的边距,我可以这样做吗?
我希望它看起来像这样:
替代文字http://i44.tinypic.com/j76kvl.jpg
我可以用Javascript + CSS做到这一点.我可以用CSS做到吗?
答:
是的,绝对定位是可能的.
#container {
width: 380px;
background-color: #DDD;
border: 2px solid #666;
position: absolute;
top: 20px; /* margin from top */
bottom: 20px; /* margin from bottom */
left: 50%; /* start left side in middle of window */
margin-left: -190px; /* then, reverse indent */
overflow: auto; /* scrollbar as necessary */
}
Run Code Online (Sandbox Code Playgroud)
结果:
替代文字http://i42.tinypic.com/33vj3nq.jpg
感谢keithjgrant的回答.请参阅http://jsbin.com/otobi上的所有代码.
尝试绝对定位:
#container {
position: absolute;
top: 20px;
bottom: 20px;
}
Run Code Online (Sandbox Code Playgroud)
它在 IE6 中可能很奇怪(什么不是?),但是如果你用 google 搜索一下,有很多技巧可以尝试。有些包括添加clear: both规则或将绝对定位的 div 包装在另一个 div 中。
应该overflow: auto使滚动条的行为如图所示。
编辑: 或者,您可以向包装器 div 添加 20px 内边距,然后将容器设置为height: 100%无边距,并且它应该填充到其包装器的内边距。