html - 如何使用 flexbox 在中心底部对齐元素

标签 html css button flexbox

我是初学者,我正在尝试在父元素底部对齐 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 元素时却无法正常工作这种情况 - 这是因为 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>

关于html - 如何使用 flexbox 在中心底部对齐元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54673767/

相关文章:

html - flexbox 在 firefox 和 chrome 中的行为不一致?

android - 带确定/取消按钮的 AlertDialog

javascript - 滚动到顶部按钮跳转而不是滚动

html - 在书写模式中设置垂直居中

html - 将另一个 css 类应用于元素

jquery - 如何在空时隐藏/删除 DIV

javascript - 我的 setInterval 没有改变,即使我的变量是

css - 如何使用 LESS.js 向 Bootstrap 3 中的导航栏添加渐变

android - 对多个按钮使用相同的 id

jquery - 我想在 div 中加载 html 页面