How to align button right in a flex container?

Viewed 9954

I don't know how to float my button right and I hope someone can help me out here.

enter image description here

The yellow color shows the background of the div. The width of the div is set to 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>

What am I doing wrong?

3 Answers

Floats do not work in a flex container

Use align-self:flex-end instead

.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>

.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>

Floats do not work with flex.

There are two approaches that you can take here.

Approach #1: Use align-self: flex-end on the button. This would make the button appear in the rightmost corner of your parent.

Approach #2: In case you want more control over the position of the button in terms of alignment with the text area, you can wrap the button in a div and keep the float right on the button.

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*/
}
Related