In this article, we’ll walk through several ways to make a sidebar with CSS: We’ll cover static sidebars, fixed and sticky sidebars, full-page sidebars, sidebars in CSS grids, and, finally, collapsible sidebars. That’s a lot to learn, so let’s dive in.
How to Create a Sidebar in CSS
The simplest way to implement a sidebar is with a static sidebar element (highlighted in blue below) that spans the height of the page and is positioned on the side of the screen.
A fixed sidebar remains in the same place relative to the viewport (i.e. the visible browser window) when the user scrolls. For example, this sidebar stays pinned to the top corner of the screen:
As you can see, the sidebar is fixed and spans the full height of the browser window. This will always be the case, no matter the height dimension of the viewport.
How to Create a Grid Sidebar in CSS
您可以使用CSS grid layoutto create a sidebar element — set your leftmost or rightmost grid item to extend to the bottom of the grid (or as far down as you want it to go), and you’ll end up with something like this:
这是上述示例的HTML和CSS代码:
<! - html->
1
2
3
4
5
6
7
8
9
10
11
12
13
/* CSS */
#网格容器{ display: grid; grid-template-columns: auto auto auto; 网格间隙:8px; 填充:8px; }
This sidebar element will be positioned相对的by default, meaning it will move upwards as the user scrolls downward. You can turn this sidebar element into a sticky element by adding the sticky CSS declarations to the first box element:
/* CSS */
#box-1 { grid-row-start: 1; 网格末端:7;/* substitute this value for your sidebar’s vertical row height */ 高度:200px; position: sticky; top: 0px; }
And瞧,侧边栏棒:
How to Create a Collapsible Sidebar in CSS
Finally, let’s cover how to create a collapsible sidebar. These can be handy for次要导航并通过隐藏非必需项目来保存页面空间。