Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  91] [ 5]  / answers: 1 / hits: 20982  / 6 Years ago, wed, january 24, 2018, 12:00:00

I'm trying to create a grid of squares to provide some navigation features.


Squares meaning that the width and height of the colored areas will be equal.


I have it working with js, but I would prefer a CSS only solution. I'm working with bootstrap.


<div class="container">
<div class="row">
<div class="col-4" style="background-color: lightgray"></div>
<div class="col-4" style="background-color: lightgreen"></div>
<div class="col-4" style="background-color: lightgray"></div>
<div class="col-4" style="background-color: lightgreen"></div>
<div class="col-4" style="background-color: lightgray"></div>
<div class="col-4" style="background-color: lightgreen"></div>
</div>
</div>

var divs = $(".row > div");
var width = divs.width();
divs.height(width)

How can I achieve this with css only?


More From » jquery

 Answers
28

You can use this trick: https://mademyday.de/height-equals-width-with-pure-css/


Here is a working fiddle: https://jsfiddle.net/65mhv1cp/


basically, you can add a class to your squares, call it square


<div class="row">
<div class="col-xs-4 square" style="background-color: lightgray"></div>
<div class="col-xs-4 square" style="background-color: lightgreen"></div>
<div class="col-xs-4 square" style="background-color: lightgray"></div>
<div class="col-xs-4 square" style="background-color: lightgreen"></div>
<div class="col-xs-4 square" style="background-color: lightgray"></div>
<div class="col-xs-4 square" style="background-color: lightgreen"></div>
</div>

The CSS would be:


.square:before{
content: "";
display: block;
padding-top: 100%; /* initial ratio of 1:1*/
}

Read more in the link to understand how/why this works.


[#55374] Sunday, January 21, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cartersinceren

Total Points: 442
Total Questions: 116
Total Answers: 106

Location: San Marino
Member since Thu, Jun 30, 2022
2 Years ago
;