我有一个主要的 div,它应该使页面可滚动。在这个 div 的两边都有一个侧边栏。我想要的与现在的唯一区别是侧边栏应始终位于顶部(position: fixed;
)
我已经尝试了所有方法,但它不起作用。如果我把 position: fixed;
放在 .fixed
上,宽度就不再是 100% 而是里面实际内容的宽度了。如果我设置 width: 100%
,则宽度变为视口(viewport)的 100%。
仅使用 CSS 是否可行?
JSFiddle:http://jsfiddle.net/6yWNv/
侧边栏 1<div id="wrapper">
<div class="contents">
<p>Lorem ipsum dolor sit amnet.</p>
</div>
</div>
<div class="sidebar">
<div class="contents">
<div class="fixed">
Sidebar 2
</div>
</div>
</div>
html, body {边距: 0;填充:0;
#wrapper {
width: 54%;
float: left;
background: #0FF;
}
.sidebar {
width: 23%;
float: left;
}
.sidebar .contents {
margin: auto;
background: #F00;
min-width: 100px;
width: 55%;
height: 100px;
}
.sidebar .contents .fixed {
background: #0F0;
}
最佳答案
诀窍是在侧边栏上设置position:fixed
(分别用left:0
和right:0
),然后添加margin-left:23%
到 #wrapper
:
#wrapper {
width: 54%;
margin-left: 23%;
background: #0FF;
}
.sidebar {
width: 23%;
position: fixed;
left:0; top: 0;
}
#wrapper + .sidebar { /* target second sidebar */
left: inherit; /* reset left */
right:0;
}
如果您希望绿色侧边栏保留在原位,但红色框移开,那么这样的事情应该可行:
.sidebar {
width: 23%;
float: left;
position: relative; /* so sub-containers are relative to sidebar */
}
.sidebar .contents {
margin: auto;
background: #F00;
min-width: 100px;
width: 100%; /* relative to sidebar */
height: 100px;
}
.sidebar .contents .fixed {
background: #0F0;
position: fixed; /* starts a new context... */
width: 23%; /* so this is not relative to sidebar *.
}
关于html - 如何将固定的 div 居中放置在另一个 div 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20621224/