Display two buttons in a row with flexbox and control alignment

Viewed 7223

Supposedly I have buttons, I want to display these buttons by 2 in a row. I'm not sure how I can display the buttons with a specific width in 2 in a row and have the control to display them left, center, or right. Wanted outcome would be something like this:

enter image description here

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.button {
  width: 190px;
  border: 1px solid red;
}
<div class="container">
  <button class="button">1</button>
  <button class="button">2</button>
  <button class="button">3</button>
  <button class="button">4</button>
</div>

2 Answers

Can you set the width of the container? Then set margin-left/margin-right to auto to align the buttons?

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 380px;
  margin-left: auto;
  margin-right: auto;
}

.button {
  width: 190px;
  border: 1px solid red;
}
<div class="container">
  <button class="button">1</button>
  <button class="button">2</button>
  <button class="button">3</button>
  <button class="button">4</button>
</div>

You can give flex: 0 50% to child elements. It's can force it to arrange 2 items per row.

.container {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 20rem;
  /* Aligning elements left, center and right in flexbox */
  /* float: left; */
  margin: auto;
  /* float: right; */
}

.button {
  border: 1px solid red;
}

.container>button {
  flex: 0 50%;
}
<div class="container">
  <button class="button">Button 1</button>
  <button class="button">Button 2</button>
  <button class="button">Button 3</button>
  <button class="button">Button 4</button>
</div>

Related