将粘性侧边栏定位在居中的div旁边



我正试图通过添加粘性侧边栏来自定义我的博客布局。我设法找到了位置:除了粘性工作,但我不知道如何把积木放在我想要的地方。

我希望主块居中,侧边栏就在主块旁边。以下是我的目标示例:https://theme-next.js.org/除了我希望主块居中。这是我想要的布局

我试过在侧边栏中使用左边距,但在较小的窗口中效果不佳,因为左边距是恒定的,在较小的窗中会将真实内容推开。这就是使用左边缘的情况

(我不知道为什么粘性剂量在这里不起作用,但它在我的网站上很好用。我想知道的只是如何将它们定位在我想要的位置。

.wrapper {
display: flex;
justify-content: space-between;
}
.sidebar {
width: 80px;
background-color: #FF0000;
position: webkit-stiky;
position: sticky;
align-self: flex-start;
height: 1000px;
}
.main {
width: 100px;
background-color: #CFCFCF;
margin: auto;
height: 1600px;
}
.header {
background-color: #F3FF00;
width: 150px;
margin: auto;
}
<div class="header">
<p>
this is centered header
</p>
</div>
<div class="wrapper">
<div class="sidebar">
<p> sidebar here</p>
</div>
<div class="main">
<p>
I want this block to be centered;
</p>
</div>
</div>

这里需要做一些事情:

  1. sticky侧边栏设置一个top属性,否则它将不会粘住
  2. 使您的main元素成为flex父元素,因为我们需要偏移其子元素以使其与标头居中
  3. main元素创建一个inner元素,这样您就可以将其向左移动80px以适应侧边栏的宽度

.wrapper {
display: flex;
position: relative;
}
.sidebar {
width: 80px;
height: 1000px;
background-color: #FF0000;
position: sticky;
/* you need a top position set for sticky */
top: 0;
}
.main {
height: 1600px;
background-color: #eeeeee;
/* This needs to be a flex parent */
display: flex;
justify-content: center;
/* This element needs to be 100% MINUS the sidebar width of 80px */
flex: 1 0 calc(100% - 80px);
}
.main-inner {
width: 100px;
position: relative;
background-color: #CFCFCF;
/* Move the inner element 80px to the left */
margin-left: -80px;
text-align: center;
}
.header {
background-color: #F3FF00;
width: 150px;
margin: 0 auto;
}
<div class="header">
<p>this is centered header</p>
</div>
<div class="wrapper">
<div class="sidebar">
<p>sidebar here</p>
</div>
<div class="main">
<div class="main-inner">
<p>I want this block to be centered;</p>
</div>
</div>
</div>

然而,我相信这才是你真正想要的:

  1. 将标头也设为flex父级

.wrapper {
display: flex;
position: relative;
}
.sidebar {
width: 80px;
height: 1000px;
background-color: #FF0000;
position: sticky;
/* you need a top position set for sticky */
top: 0;
}
.main {
height: 1600px;
background-color: #eeeeee;
/* This needs to be a flex parent */
display: flex;
justify-content: center;
/* This element needs to be 100% MINUS the sidebar width of 80px */
flex: 1 0 calc(100% - 80px);
}
.main-inner {
width: 100px;
position: relative;
background-color: #CFCFCF;
/* Move the inner element 80px to the left */
text-align: center;
}
.header {
display: flex;
justify-content: flex-end;
}
.header-inner {
background-color: #F3FF00;
text-align: center;
width: calc(100% - 80px);
background-color: #F3FF00;
}
<div class="header">
<div class="header-inner">
<p>this is centered header</p>
</div>
</div>
<div class="wrapper">
<div class="sidebar">
<p>sidebar here</p>
</div>
<div class="main">
<div class="main-inner">
<p>I want this block to be centered;</p>
</div>
</div>
</div>

最新更新