抱歉这是一个非常愚蠢的问题。
我有一个div #header和一个div #content。 #content的内容可能比视口宽,甚至更宽。在这种情况下,会出现一个水平滚动条,这很好。
但是,对于水平滚动条,我希望#header占据宽度的100%,而不是视口,而是文档的宽度;这样当用户滚动时不会中断。
以下是代码:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>test</title>
</head>
<body>
<div id="header" style="background:red;">this should take the entire width, even when
scrolling to the right</div>
<div id="content" style="min-width:1000px; min-height:1000px; border:1px solid green;">this causes a horizontal
scrollbar on narrow displays</div>
</body></html>
以下是一个示例:http://a3nm.net/share/test_157235.html
我希望红色的#header div与下面的#contents一样宽。对于这个例子,我模仿了#content宽度与最小宽度,但总的来说我想要一个方法,无论#contents的宽度是多少都有效。
请注意,如果#content足够高,导致垂直滚动,我希望当用户向下滚动时,标题会滚动显示内容的顶部。
我确信这可以在Javascript中完成,但我会寻找纯CSS解决方案。
谢谢!
答案 0 :(得分:3)
html, body
{
padding: 0;
margin: 0;
}
接下来,将#header和#content放在div #wrapper中,其样式为:
#wrapper
{
position:absolute;
min-width: 100%;
}
这使得包装器占据视口宽度的至少100%(由于CSS重置导致没有水平滚动条),并且它是绝对的,如果需要水平滚动条,它会以某种方式占用文档宽度的100%因为#content。
完整的解决方案:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>test</title>
<style type="text/css">
html,body {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div style="position:absolute; min-width: 100%;">
<div id="header" style="background:red;">this should take the entire width, even when
scrolling to the right</div>
<div id="content" style="min-width:1000px; min-height:1000px; border:1px solid green;">this causes a horizontal
scrollbar on narrow displays</div>
</div>
</body></html>
答案 1 :(得分:0)
您是否尝试过Eric Meyers重置css? 您需要将#header('s)填充和边距设置为0.
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}