我是初学者,我试图在父元素底部对齐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>
使用列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>
我认为button
不能是flex容器,它们只能是flex元素。
这段代码应该可以工作,但我不确定这是否是最好的方法。它适用于Chrome,您可能需要尝试不同的浏览器。
.sidebarBtn {
width: 50px;
height: 500px;
border: none;
background-color: beige;
cursor: pointer;
}
.sidebarBtnContent {
width:100%;
height: 100%;
display: flex;
align-items: flex-end;
justify-content: center;
}
.sidebarBtnContent span {
width: 35px;
height: 3px;
background-color: black;
}
<button class="sidebarBtn">
<span class="sidebarBtnContent">
<span></span>
</span>
</button>