我有一个.sidebar
和一个.content
div,包含在flexbox中。我想在保持侧边栏固定的同时使内容可滚动。
约束
问题
如果我相对定位,侧边栏和内容都会滚动:fiddle
.flex{
position: relative;
display: flex;
flex-direction: row;
max-width: 600px;
margin: auto;
border: 1px solid green;
}
.flex > *{
border: 1px solid green;
}
.sidebar{
width: 200px;
}
.content{
flex: 1;
overflow-y: auto;
}
.content p{
font-size: 48px;
}
如果我绝对定位它,滚动条会留下美丽的右角以包裹600px容器:fiddle
*{
box-sizing: border-box;
}
.flex-wrapper{
position: absolute;
top: 0;
left: 0;
right: 0;
width: 100%;
height: 100%;
max-width: 600px;
margin: auto;
}
.flex{
display: flex;
flex-direction: row;
border: 1px solid green;
height: 100%;
}
.flex > *{
border: 1px solid green;
}
.sidebar{
width: 200px;
}
.content{
flex: 1;
overflow-y: auto;
}
.content p{
font-size: 48px;
}
如何让滚动条停留在屏幕的右边缘而不是环绕固定宽度的div?我该怎么做?
答案 0 :(得分:1)
不需要使用Flexbox,只需移除包装并将侧栏固定在固定位置。
此外,我使用媒体查询来控制两者的左边缘。
html, body {
margin: 0;
}
* {
box-sizing: border-box;
}
.sidebar, .content {
border: 1px solid green;
}
.sidebar {
position: fixed;
top: 0;
bottom: 0;
left: calc(50% - 300px);
width: 200px;
}
.content {
max-width: 400px;
margin-left: calc(50% - 100px);
}
.content p {
font-size: 48px;
}
@media (max-width: 600px) {
.sidebar {
left: 0;
}
.content {
margin-left: 200px;
}
}

<div class="sidebar">
<ul>
<li>Home</li>
<li>About</li>
<li>Contacts</li>
<li>Monkeys</li>
<lI>Pigeons</lI>
</ul>
</div>
<div class="content">
<p>
We have got the best monkeys in entire europe.
</p>
<p>
We have also got some really good pigeons.
</p>
<p>
One pigeon scored more than 1500 in 2016 SAT exams.
</p>
<p>
The monkey was quite jealous of him to be honest.
</p>
<p>
But they are still besties so far... and will be forever
</p>
</div>
&#13;