bu246 bu246 - 3 months ago 6
CSS Question

Center a button under 3 divs

I have 3 divs (colored squares) and a button.

How can I center the button under the divs?

With my current code the button appears in the same line as

#squares
and it's floating to the left. Thanks for your answers.



#div1 {
background-color: red;
width: 100px;
height: 100px;
margin-right: 10px;
}
#div2 {
background-color: green;
width: 100px;
height: 100px;
margin-right: 10px;
}
#div3 {
background-color: blue;
width: 100px;
height: 100px;
}
#squares {
display: flex;
position: absolute;
margin-left: 35%;
}
#button {
width: 100px;
height: 50px;
clear: both;
}

<div id="squares">
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
</div>
<div id="button">
<button>Click me!</button>
</div>




Answer

Since you're already using flexbox, there are multiple solutions, all of them relatively simple.

Here's one:

  • Wrap both containers in a parent container.
  • Add display: flex and flex-direction: column to this new container.
  • Now you can easily align the squares and the button both vertically and horizontally.

#container {
  display: flex;
  flex-direction: column;
}
#div1 {
  background-color: red;
  width: 100px;
  height: 100px;
}
#div2 {
  background-color: green;
  width: 100px;
  height: 100px;
  margin: 0 10px;
}
#div3 {
  background-color: blue;
  width: 100px;
  height: 100px;
}
#squares {
  display: flex;
  align-self: center;
  margin-bottom: 10px;
}
#button {
  align-self: center;
  text-align: center;
  width: 100px;
  height: 50px;
}
<div id="container">
  <div id="squares">
    <div id="div1"></div>
    <div id="div2"></div>
    <div id="div3"></div>
  </div>
  <div id="button">
    <button>Click me!</button>
  </div>
</div>

Comments