Tahmid Khan Nafee Tahmid Khan Nafee - 4 months ago 17
HTML Question

How to center multiple div elements within a parent div?

I am trying to center smaller divs within a larger div. My code looks like this:

Codepen Link



div.box-collective {
background-color: grey;
width: 100%;
}

div.box {
width: 100px;
height: 100px;
border: 1px solid black;
display: inline-block;
margin: 10px;
}

<div class="container">
<h1>My boxes</h1>

<div class="box-collective">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>





Since its impossible to explain what I am trying to do with words, please look at these pics to get a better idea:

enter image description here

In the above case, the screen width is large (desktop). Basically, my code looks like the top version. I result I want is the one on the bottom, that is, the group of boxes centered perfectly.

enter image description here

In this case, the screen is small, and since each box is inline-block, they automatically go to a new line when the screen is resized. However, once again I want to center them, similar to the right pic.

How can I achieve this using pure CSS? Any help is appreciated.

Answer

You can simply put text-align:center; on your div.box-collective class.

div.box-collective {
    background-color: grey;
    width: 100%;
    text-align:center;
}

div.box {
    width: 100px;
    height: 100px;
    border: 1px solid black;
    display: inline-block;
    margin: 10px;
}
<div class="container">
  <h1>My boxes</h1>

    <div class="box-collective">
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
      <div class="box"></div>
    </div>
</div>