使用CSS定位DIV元素

4

假设我有以下的DIV:

<div id="top">Page header</div>
<div id="main">Main content</div>
<div id="sidebar">Sidebar content</div>
<div id="bottom">Page footer</div>

如何使用CSS将侧边栏DIV放置在主DIV的右侧,并将其设置为总宽度的20%?

我还想在四个DIV之间留出一些边距,以使布局不显得过于拥挤。

希望它能在“所有”浏览器中都能正常工作,包括该死的IE6 ...

6个回答

3

将主要内容和侧边栏放在包装器中,您可以设置包装器的大小/位置,并保留您的布局。

#top {
  /* top stuff */
}
#wrapper {
  width: 800px;
  margin: 0px auto; /* centers on page */
}
#main {
  float: left;
  width: 80%;
  margin-right: 10px;
}
#sidebar {
  float: left; /* by floating left here you have a greater control over the margin */
  width: 20%;
}
#bottom {
  /* bottom stuff */
}

0

尝试:

html, body, div { margin: 0; padding: 0; border: 0 none; } /* primitive reset CSS */
#main { float: left; width: 80%; }
#sidebar { float: right; width: 20%; }
#bottom { clear: both; }

对于这种情况,使用重置CSS(还有其他的)非常重要,因为不同的浏览器对于边框、外边距和内边距等默认值是不同的。


0
<div id="top">Page header</div>
<div id="main">
    <div id="content">Main content</div>
    <div id="sidebar">Sidebar content</div>
</div>
<div id="bottom">Page footer</div>


#top, #main, #bottom { float: left; clear: both; width: 100%; margin-bottom: 1em; }
#sidebar { float: right; width: 20%; }
#content { float: right; }

0

0

非常非常重要的是,您将文档类型设置为严格,就像这样:

如果你这样做,就不需要清除你的CSS(有一些例外),而可以直接使用正确的盒模型。

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接