我是初学者,我正在尝试在父元素底部对齐 span
元素。为此,我使用了下面的 CSS,但为什么它不起作用:
.sidebarBtn {
position: absolute;
top: 0;
right: -50px;
width: 50px;
height: 500px;
border: none;
display: flex;
justify-content: center;
align-items: flex-end;
background-color: beige;
outline: none;
cursor: pointer;
}
.sidebarBtn span {
width: 35px;
height: 3px;
background-color: black;
}
<button class="sidebarBtn">
<span></span>
</button>
最佳答案
使用 column flexbox 并使用 justify-content: flex-end
将其对齐到底部 - 请参见下面的演示:
.sidebarBtn {
position: absolute;
top: 0;
right: 50px;
width: 50px;
height: 500px;
border: none;
display: flex;
flex-direction: column; /* ADDED */
justify-content: flex-end; /* CHANGED */
align-items: center; /* CHANGED */
background-color: beige;
outline: none;
cursor: pointer;
}
.sidebarBtn span {
width: 35px;
height: 3px;
background-color: black;
}
<button class="sidebarBtn"><span></span></button>
但您可能会想,为什么您的代码在 div
而不是 button
元素时却无法正常工作这种情况 - 这是因为 button
或 fieldset
元素未设计为 flex 容器。当您将 flexbox
放在按钮中时,看看一切是如何正常的:
.sidebarBtn {
background-color: beige;
outline: none;
cursor: pointer;
position: absolute;
top: 0;
right: 50px;
width: 50px;
height: 500px;
}
.sidebarBtn>span {
border: none;
display: flex;
justify-content: center;
align-items: flex-end;
height: 100%;
}
.sidebarBtn>span>span {
width: 35px;
height: 3px;
background-color: black;
}
<button class="sidebarBtn">
<span>
<span></span>
</span>
</button>
关于html - 如何使用 flexbox 在中心底部对齐元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54673767/