如何在 flex 容器中将按钮右对齐?

8

我不知道如何将我的按钮向右浮动,希望有人能在这里帮助我。

在此输入图片描述

黄色显示了div的背景。 div的宽度设置为50%。

.faq {
  width: 100%;
  padding: 12px 20px;
  display: block;
  box-sizing: border-box;
  width: 50%;
  margin: auto;
  margin-top: 30px;
}

.outerDiv {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  margin-top: 20px;
  background-color: yellow;
}

.save {
  float: right;
  background-color: red;
}
<div class="outerDiv">
  <h2>New FAQ</h2>
  <input type="text" class="faq">
  <br>
  <button class="save" mat-raised-button color="primary">Primary</button>
</div>

我做错了什么?


很可能,这里(flexbox)outerDiv的样式会覆盖按钮上的浮动样式。您可以在.save按钮中使用flexbox来右对齐,例如使用align-self等。此外,请提供一个完整的可运行示例,使用Stackoverflow片段或代码沙箱。 - Abdulrahman Ali
我建议您完全放弃使用浮点数。除了可能经典的例外情况,如让文本环绕图像,几乎总有更好的方法。 - isherwood
你应该使用margin-left:auto;属性。 - pullidea-dev
3个回答

9

浮动在 flex 容器中不起作用

请使用 align-self:flex-end 来代替

.faq {
  padding: 12px 20px;
  display: block;
  box-sizing: border-box;
  width: 50%;
  margin: auto;
  margin-top: 30px;
}

.outerDiv {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  margin-top: 20px;

  background-color: yellow;
}

.save {
   align-self:flex-end;
  background-color: red;
}
<div class="outerDiv">
    <h2>New FAQ</h2>
    <input type="text" class="faq">
    <br>
    <button class="save" mat-raised-button color="primary">Primary</button>
</div>


谢谢!align-self: flex-end + margin-right: 25% 对我起了作用 :-) - IonicMan

1

浮点数与flex不兼容。

这里有两种方法可供选择。

方法1: 在按钮上使用align-self: flex-end。这将使按钮出现在父元素的最右侧。

方法2: 如果您想更精确地控制按钮与文本区域的对齐位置,可以将按钮包装在一个div中,并在按钮上保持右浮动。

HTML

<div class="button-wrapper">
  <button class="save" mat-raised-button color="primary">Primary</button>
</div>

CSS

.button-wrapper {
    width: 50%; /* same as the width of your input*/
}

1

.faq {
  width: 100%;
  padding: 12px 20px;
  display: block;
  box-sizing: border-box;
  width: 50%;
  margin: auto;
  margin-top: 30px;
}

.outerDiv {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  margin-top: 20px;

  background-color: yellow;
}

.save {
margin-left:auto;
  background-color: red;
}
<div class="outerDiv">
    <h2>New FAQ</h2>
    <input type="text" class="faq">
    <br>
    <button class="save" mat-raised-button color="primary">Primary</button>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接