如何使用弹性框对齐中心底部的元素

问题描述 投票:0回答:2

我是初学者,我试图在父元素底部对齐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>
html css css3 button flexbox
2个回答
2
投票

使用列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元素时工作正常 - 这是因为buttonfieldset元素不是设计为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>

0
投票

我认为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>
© www.soinside.com 2019 - 2024. All rights reserved.