我正在尝试通过添加粘性侧边栏来自定义我的博客布局。我设法让 position:sticky 正常工作,但我不知道如何将块放置在我想要的位置。
我希望主块居中,侧边栏就在主块旁边。这是我的目标示例:https://theme-next.js.org/ 除了我希望主块居中。 this is the layout I want
我已经尝试在侧边栏上使用 margin-left,但它在较小的窗口中效果不佳,因为左边距是恒定的,并且会在较小的窗口中将实际内容推开。 this is what happens by using margin-left
(我不确定为什么粘性在这里不起作用,但它在我的网站上运行良好。我只想弄清楚如何将它们放置在我想要的位置。
.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>
答案 0 :(得分:0)
您需要在这里做一些事情:
top
侧边栏设置 sticky
属性,否则它不会粘住main
元素设为 flex
父元素,因为我们需要偏移其子元素以使其与标题居中。inner
元素创建一个 main
元素,以便您可以将其向左移动 80 像素以适应侧边栏的宽度。.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>
但是,我相信这就是您真正想要的:
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>