Jeel Shah Jeel Shah - 3 months ago 14
CSS Question

Centering multiple side-by-side divs

I am trying to make multiple divs, specifically five and center them all. I have used the

display:inline-block
to get them to be side by side but then when I use
margin: 0 auto
, the
display:inline-block
seems to get negated and then it's a vertical strip going down the page.

Below is my code:



div {
width: 50px;
height: 300px;
border-radius: 0;
display: inline-block;
}
#red {
background-color: red;
}
#orange {
background-color: orange;
}
#yellow {
background-color: yellow;
}
#green {
background-color: green;
}
#blue {
background-color: blue;
}

<div class="container">
<div id="red"></div>
<div id="orange"></div>
<div id="yellow"></div>
<div id="green"></div>
<div id="blue"></div>
</div>





I tried looking at the other relevant posts on SO but they don't do it with as many divs or they use static positioning which I don't want to use.

Can someone point me in the right direction?

Answer

This happens cause the width of the container is 50px. One quick solution is to set width of container to 100%:

div {
  width: 50px;
  height: 300px;
  border-radius: 0;
  display: inline-block;
}
#red {
  background-color: red;
}
#orange {
  background-color: orange;
}
#yellow {
  background-color: yellow;
}
#green {
  background-color: green;
}
#blue {
  background-color: blue;
}
.container {
  width: 100%;
}
<div class="container">
  <div id="red"></div>
  <div id="orange"></div>
  <div id="yellow"></div>
  <div id="green"></div>
  <div id="blue"></div>
</div>

You can align to center using text-align center to container:

div {
  width: 50px;
  height: 300px;
  border-radius: 0;
  display: inline-block;
}
#red {
  background-color: red;
}
#orange {
  background-color: orange;
}
#yellow {
  background-color: yellow;
}
#green {
  background-color: green;
}
#blue {
  background-color: blue;
}
.container {
  width: 100%;
  text-align: center;
}
<div class="container">
  <div id="red"></div>
  <div id="orange"></div>
  <div id="yellow"></div>
  <div id="green"></div>
  <div id="blue"></div>
</div>

To achieve both and vertical and horizontal align you can use position: absolute to the container top: 50% left: 50% and margin-top: -150px; /* Half the height */ margin-left: -135px; /* Half the width */:

div {
    width: 50px;
    height: 300px;
    border-radius: 0;
    display:inline-block;
}
#red {
    background-color: red;
}
#orange {
    background-color: orange;
}
#yellow {
    background-color: yellow;
}
#green {
    background-color: green;
}
#blue {
    background-color: blue;
}

.container {
    width: 270px;
    position: absolute;
    top: 50%;
    left:50%;
    margin-top: -150px; /* Half the height */
    margin-left: -135px; /* Half the width */
}
<div class="container">
  <div id="red"></div>
  <div id="orange"></div>
  <div id="yellow"></div>
  <div id="green"></div>
  <div id="blue"></div>
</div>