CSS 将部分或侧边栏垂直居中

CSS vertically centering a section or sidebar

我正在尝试为页面创建侧边栏,并希望将另一个部分中的一个部分垂直居中。我试过的片段如下。 即使调整页面大小时,我也希望徽标部分保留在中心。 包含徽标的部分位于虚线边框中。即使调整大小时,我也希望整个部分位于边栏的中央。

Code Snippet Here

body{
  box-sizing: border-box;
}        
.sidebar {
            background-color: gray;
            opacity: 0.5%;
            position: fixed;
            right: 0;
            top: 0;
            height: 100%;
            width: 100px;
            border: 1px solid black;
            border-right: 0px;
            border-top: 0px;
            vertical-align: center;
            text-align: center;
            box-sizing: border-box;
        }
        
        .sidebar_logo_sec{
            margin-top:50%;
            padding-top:15px;
            padding-bottom:15px;
            height: 200px;
            width: 100px;
            vertical-align: center;
            text-align: center;
            border:1px dashed black;
        }

        .sidebarLogo {
            height: 52px;
            width: 52px;
            border-radius: 50%;
            border: 2px solid #424242;
            margin-bottom: 40px;
            text-align: center;
        }
<body>
    <section class="sidebar">
        <article class="sidebar_logo_sec">
            <section>
                <div>
                    <img class="sidebarLogo" src="github.svg" alt="github">
                </div>
            </section>
            <section>
                <div><img class="sidebarLogo" src="linkedin.svg" alt="linked in"></div>
            </section>
        </article>
    </section>
</body>

看起来很完美use case for flexbox

如果将这些添加到边栏的现有属性中:

.sidebar {
   display: flex;
   align-items: center;
   justify-content: center;
   // other properties follow
}

虚线部分应该很好地垂直居中。

Fiddle here

由于您的 .sidebar 已固定位置,请尝试删除 top: 0right: 0 并替换为:

.sidebar {
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}