我有一个.sidebar
和一个.content
div,包裹在一个弹性框中。我想使内容可滚动,同时保持侧边栏固定。
约束
- 我不能使用Javascript
- 容器最大宽度必须为 600 像素
问题
如果我相对定位它,侧边栏和内容都会滚动:小提琴
.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 容器:小提琴
*{
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?
无需为此使用 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>