CSS 如何正确实现固定侧边栏?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15590803/
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
How to implement fixed sidebar correctly?
提问by Jakemmarsh
I'm trying to accomplish this design: Where the sidebar will be fixed, but the right side (the main content) will scroll vertically (and potentially horizontally if the user's browser window is smaller). What is the best way to achieve this?
我正在尝试完成此设计: 侧边栏将被固定,但右侧(主要内容)将垂直滚动(如果用户的浏览器窗口较小,则可能水平滚动)。实现这一目标的最佳方法是什么?
I tried making the sidebar be "fixed" with a fixed width of 200px, and then the main content just has a margin-left of 200px. However, if the user's browser is then smaller than the main content, the sidebar overlaps all the content as the user tries to scroll horizontally.
我尝试将侧边栏“固定”为 200 像素的固定宽度,然后主要内容的边距为 200 像素。但是,如果用户的浏览器小于主要内容,则当用户尝试水平滚动时,侧边栏会覆盖所有内容。
Is there a smarter way to achieve this? Thanks!
有没有更聪明的方法来实现这一目标?谢谢!
回答by Daniel
Use the content div as your container for the page.
使用内容 div 作为页面的容器。
.sidebar {
position: fixed;
width: 200px;
height: 400px;
background: #000;
}
.content {
margin-left: 200px;
height: 500px;
width: auto;
position: relative;
background: #f00;
overflow: auto;
z-index: 1;
}
.info {
width: 1440px;
height: 300px;
position: relative;
background: #f55;
}
<div class="sidebar"></div>
<div class="content">
<div class="info"></div>
</div>
Your content will need to be the container to put the page in. The values here are my test to see if I am correct in this. If your width and height exceeds the values you set for content, the scroll bars will appear.
您的内容需要是放置页面的容器。这里的值是我的测试,看看我是否正确。如果您的宽度和高度超过您为内容设置的值,则会出现滚动条。
Have a fiddle: http://jsfiddle.net/djwave28/JZ52u/
有一个小提琴:http: //jsfiddle.net/djwave28/JZ52u/
edit: responsive sidebar
编辑:响应式侧边栏
To have a responsive fixed sidebar, simply add a media-query.
要拥有响应式固定侧边栏,只需添加一个媒体查询。
Example:
例子:
@media (min-width:600px) {
.sidebar {
width: 250px;
}
.content {
margin-left: 250px;
}
}
Here's another fiddle: http://jsfiddle.net/djwave28/JZ52u/363/
这是另一个小提琴:http: //jsfiddle.net/djwave28/JZ52u/363/
回答by Evan Mosseri
Here is an alternative: http://jsfiddle.net/BoyWonder/8mVQX/embedded/result/
这是一个替代方案:http: //jsfiddle.net/BoyWonder/8mVQX/embedded/result/
body{
padding-left:200px;
margin:0;
}
div#sidebar{
position:fixed;
height:100%;
width:200px;
top:0;
left:0;
background:grey;
}
div#content{
background:black;
width:100%;
height:1600px;
}