HTML/CSS:如何使侧边栏和内容相互跟随
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3194983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML/CSS: How to make the sidebar and content follow each other
提问by Adam
I need a sidebar and a content area. I want to have equal height for both sections. So if I want to specify a background color for the sidebar, it will follow the content area even if the sidebar's contents are not as tall as the content section and vice versa. I want to make this in pure HTML and CSS only, so no javascript tricks.
我需要一个侧边栏和一个内容区域。我希望两个部分的高度相等。因此,如果我想为侧边栏指定背景颜色,即使侧边栏的内容没有内容部分那么高,它也会跟随内容区域,反之亦然。我只想在纯 HTML 和 CSS 中制作它,所以没有 javascript 技巧。
采纳答案by NotMe
The only real way of doing this in a cross browser fashion is with tables.
以跨浏览器方式执行此操作的唯一真正方法是使用表格。
As content is added to the sidebar cell below, it will force the entire row to expand which in turn will force the contentArea cell to expand as well. You can style those individually with css.
当内容添加到下面的侧边栏单元格时,它会强制扩展整行,这反过来又会强制扩展 contentArea 单元格。您可以使用 css 单独设置样式。
<style>
#sideBar { vertical-align:top;}
#contentArea { vertical-align:top;}
</style>
<table>
<tr>
<td id="sideBar">SideBar</td>
<td id="contentArea">content area</td>
</tr>
</table>
回答by You
This excellent articleon A List Apartbuilds such a layout from scratch, and also contains some interesting links to other articles on the subject, such as Faux Columns(also on ALA).
这篇关于A List Apart 的优秀文章从头开始构建了这样的布局,并且还包含一些指向有关该主题的其他文章的有趣链接,例如Faux Columns(也在 ALA 上)。
回答by MistaPrime
Basically just set the height of the sidebar to be 100% and it will follow the parent element's height. In the example below its the container element. No matter it's height, sidebar's height will be 100% and therefore always be same height as container.
基本上只需将侧边栏的高度设置为 100%,它将遵循父元素的高度。在下面的示例中,它是容器元素。无论高度如何,侧边栏的高度都是 100%,因此始终与容器高度相同。
<div id="wrapper">
<div id="container">
<div id="sidebar"></div>
</div>
</div>
<style>
#wrapper {}
#container {min-height:500px;} (or whatever you want for the height)
#sidebar {height:100%;}
</style>