好吧,这让我抓狂。
我想在我的文档周围加上边框。它应该很好地绕过整个窗口/视口(viewport)。所以我定义:
body {
border: 1px solid red;
}
当我的文档处于 quirks 模式时,这工作正常。至少在 IE 中,这是我的主要目标。红色边框出现在我页面的最边缘,显然是因为预定义的 CSS body
和 html
被设置为填充屏幕。
当通过设置 HTML 4.01 严格 DOCTYPE 进入标准模式时,body
和 html
折叠为 真实(较小的)尺寸content, border 绘制在屏幕中间。所以我定义:
body, html {
padding: 0px;
margin: 0px;
border: 0px none;
width: 100%;
height: 100%;
}
body {
border: 1px solid red;
}
然后我得到 — 滚动条,正好滚动 一个像素 以显示底部/右侧边框。但是,我希望该边框立即可见。
是否有一个 no-bullshit(如“高度:99.9%;”、“溢出:隐藏;”或“切换回怪癖模式”)方法来获得 100% 的边框,而没有不必要的滚动条?仅 IE 就可以,当然,跨浏览器会更好。
最佳答案
正如 SpliFF 已经提到的,问题是因为默认 (W3C) box model是“content-box”,这导致边框在 width
和 height
之外。但是您希望它们在您指定的 100% 宽度和高度范围内。一种解决方法是选择 border-box 框模型,但如果不恢复到 quirks 模式,则无法在 IE 6 和 7 中执行此操作。
另一种解决方案也适用于 IE 7。只需将 html
和 body
设置为 100% 高度并将 overflow
设置为 hidden
即可摆脱窗口的滚动条。然后你需要插入一个绝对定位的包装器 div 来获取红色边框和所有内容,设置所有四个 box offset properties到 0
(因此边框粘在视口(viewport)的边缘)和 overflow
到 auto
(将滚动条放在包装器 div 中)。
只有一个缺点:IE 6 不支持同时设置 left
和 right
以及 top
和 底部
。唯一的解决方法是使用 CSS expressions (在条件注释中)明确地将包装器的宽度和高度设置为视口(viewport)的大小减去边框的宽度。
为了更容易看到效果,在下面的例子中我将边框宽度扩大到5像素:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Border around content</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html, body {
height: 100%;
overflow: hidden;
}
#wrapper {
position: absolute;
overflow: auto;
left: 0;
right: 0;
top: 0;
bottom: 0;
border: 5px solid red;
}
</style>
<!--[if IE 6]>
<style type="text/css">
#wrapper {
width: expression((m=document.documentElement.clientWidth-10)+'px');
height: expression((m=document.documentElement.clientHeight-10)+'px');
}
</style>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- just a large div to get scrollbars -->
<div style="width: 9999px; height: 9999px; background: #ddd"></div>
</div>
</body>
</html>
附注:我刚刚看到您不喜欢overflow: hidden
,嗯……
更新:我设法绕过了 overflow: hidden
的使用,方法是使用四个贴在视口(viewport)边缘的 div 伪造边框(您不能只叠加带有全尺寸 div 的整个视口(viewport),因为它下面的所有元素将无法再访问)。这不是一个很好的解决方案,但至少正常的滚动条保持在原来的位置。我无法让 IE 6 使用 CSS 表达式模拟固定定位(右侧和底部的 div 有问题),但它看起来很糟糕,因为这些表达式是 very expensive渲染变得非常缓慢。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Border around content</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#border-t, #border-b, #border-l, #border-r {
position: fixed;
background: red;
z-index: 9999;
}
#border-t {
left: 0;
right: 0;
top: 0;
height: 5px;
}
#border-b {
left: 0;
right: 0;
bottom: 0;
height: 5px;
}
#border-l {
left: 0;
top: 0;
bottom: 0;
width: 5px;
}
#border-r {
right: 0;
top: 0;
bottom: 0;
width: 5px;
}
</style>
</head>
<body>
<!-- just a large div to get scrollbars -->
<div style="width: 9999px; height: 9999px; background: #ddd"></div>
<div id="border-t"></div><div id="border-b"></div>
<div id="border-l"></div><div id="border-r"></div>
</body>
</html>
关于html - 围绕 100% 主体高度和宽度的边框(HTML 4.01 严格),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/886809/