Responsive Square grid with HTML and CSS


Adding a  grid  with responsive square to our web page is simple than most of us think.

CSS

.container{    
    width: 100%;
    background: lightgray;    
    display: inline-block;
}

.container div {    
    float:left;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    background-color: #1E1E1E;    
}


HTML

<div class="container">
             <!-- 1st row */ -->
            <div></div>
            <div></div>
            <div></div>
            <!-- 2nd row */ -->
            <div></div>
            <div></div>
            <div></div>
            <!-- 3rd row */ -->
            <div></div>
            <div></div>
            <div></div>
            
        </div>

In this example i have used aspect ratio 1:1 because i wanted squares in the grid. Width and padding-bottom properties can be changed as follows according to the aspect ratio you want.


Aspect ratio padding-bottom for 30% width
1:1 =width 30%
1:2 = width X 2 60%
2:1 = width X 0.5 15%
4:3 = width X 0.75 22.5%
16:9 = width X 0.5625 16.875%

Ex: if you want aspect ratio 4:3 for div inside grid CSS should be changed as this

.container{    
    width: 100%;
    background: lightgray;    
    display: inline-block;
}

.container div {    
    float:left;
    width: 30%;
    padding-bottom: 22.5%; 
    margin:1.66%;
    background-color: #1E1E1E;    
}
Refer this SOF question for more details.
Please add a comment if this was useful or you have something to add.

No comments:

Post a Comment