Search code examples
htmlcssgridcenter

Responsively center a grid of squares


I'm not really sure on how to explain this problem as I'm still relatively new to coding.

I currently have a line of 7 square divs that sit 'inline' on desktop. As the screen changes however, I would like these divs to drop via floating, but have the row itself remain centered.

Eg.

What happens (if &=edge of screen, and #=blank space) =

Desktop View
&# 1/2/3/4/5/6/7/#&

Shrinked View
&# 1/2/3/4 #####&
&# 5/6/7 #######&

What I would like to happen:

Shrinked View
&###1/2/3/4##&
&####5/6/7####&

https://jsfiddle.net/48942Lor/ - Full code.

CSS

#grid-container {width:40%;text-align:center;margin:0 auto;}

.grid-image {
    display: inline-block;
    box-sizing: border-box;
    min-height: 200px;
    min-width: 200px;
    max-width: 200px;
    width: 200px;
    float: left;
    margin: 0 auto;
}

HTML

<section id="grid-container">
<div class="grid-image" id="red"></div>
<div class="grid-image" id="orange"></div>
<div class="grid-image" id="yellow"></div>
<div class="grid-image" id="green"></div>
<div class="grid-image" id="blue"></div>
<div class="grid-image" id="indigo"></div>
<div class="grid-image" id="violet"></div>
</section>

Solution

  • That is happening because of float:left. Removing that works nicely. Here's the fiddle.