Search code examples
htmlcss

Distribute divs evenly in a horizontal line


I'm trying to distribute divs evenly in a horizontal line. I will have 3 divs on maximum width of the screen. When I resize the browser and it can't fit 3 then it will switch to two, and then one. I have found a few examples of how this is done, but none of them do it in the way I am looking for. For example what I want is this:

Full Screen width:

[------------------------------------------]
[   [--------]   [--------]   [--------]   ]
[   [        ]   [        ]   [        ]   ]
[   [        ]   [        ]   [        ]   ]
[   [--------]   [--------]   [--------]   ]
[                                          ]
[   [--------]   [--------]   [--------]   ]
[   [        ]   [        ]   [        ]   ]
[   [        ]   [        ]   [        ]   ]
[   [--------]   [--------]   [--------]   ]
[------------------------------------------]

Resized width:

[-----------------------------]
[   [--------]   [--------]   ]
[   [        ]   [        ]   ]
[   [        ]   [        ]   ]
[   [--------]   [--------]   ]
[                             ]
[   [--------]   [--------]   ]
[   [        ]   [        ]   ]
[   [        ]   [        ]   ]
[   [--------]   [--------]   ]
[                             ]
[   [--------]   [--------]   ]
[   [        ]   [        ]   ]
[   [        ]   [        ]   ]
[   [--------]   [--------]   ]
[-----------------------------]

Note that the divs are centered on the page every time.

What I was able to find are these examples which force the divs to be left and right with the borders of the div and then space is evently distributed such as example below:

[-----------------------------]
[[--------]         [--------]]
[[        ]         [        ]]
[[        ]         [        ]]
[[--------]         [--------]]
[                             ]
[[--------]         [--------]]
[[        ]         [        ]]
[[        ]         [        ]]
[[--------]         [--------]]
[                             ]
[[--------]         [--------]]
[[        ]         [        ]]
[[        ]         [        ]]
[[--------]         [--------]]
[-----------------------------]

Here are the code examples of what I tried:


Solution

  • Hope this is what you are trying to do with!!!

    #container {
      width: 100%;
      text-align: center;
    }
    
    #container>div {
      width: calc(100% / 6);
      display: inline-block;
      vertical-align: top;
      border: 1px solid red;
      text-align: center;
      margin: 2%;
      padding: 20px;
    }
    <div id="container">
      <div>1</div>
      <div>2</div>
      <div>3</div>
      <div>4</div>
      <div>5</div>
      <div>6</div>
    </div>