Easy responsive squares with CSS and jQuery

Making something responsive isn’t always the easiest thing to do, especially if you have to keep the same height and width ratio on an element. For example a square, or a couple of squares next to each other on a web page.

Image from Silverfish.nl

 

 

 

 

 

1. Add the jQuery to your <head> tag if you haven’t already.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

 

 

 

 

2. To be able to make the blocks responsive, we set a width in percentages

.square { width: 50%; padding: 20px; box-sizing: border-box; }

 

3. And now for the magic; the jQuery. In step 2 we gave the blocks the class “square”. Using this class name, we can dynamically calculate the height (the same height as the width of the blocks) to make sure that the shape becomes a square when the page loads. And also stays a square when the browser window is being resized.

<script>
// Set the block height equal to the block width
function responsiveSquares (){
var width = $('.square').outerWidth();
$('.square').css('height', width);
}

// Execute function responsiveSquares() when the page loads
$(document).ready(function(){ responsiveSquares(); });

// Execute function responsiveSquares() when browser window is being resized
$(window).resize(function(){ responsiveSquares(); });
</script>

 

 

Working example in Codepen: https://codepen.io/menno-van-der-krift/pen/GBKzJG

Full code

<!DOCTYPE html>
<html>
<head>
<title>Responsive squares</title>

<!-- import the jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
* { padding: 0; margin: 0; }
.squares-wrapper { display: flex; justify-content: space-around; }
.square { width: 30%; }

.square-1 { background: orange; }
.square-2 { background: cornflowerblue; }
.square-3 { background: indianred; }
</style>
</head>
<body>
<div class="squares-wrapper">
<div class="square square-1"></div>
<div class="square square-2"></div>
<div class="square square-3"></div>
</div>

<script>
// Get the width of the .squares class, and make the height equal to the width
function responsiveSquares() {
var width = $('.square').outerWidth();
$('.square').css('height', width);
}
responsiveSquares();

$(document).ready(function(){ responsiveSquares(); });
$(window).resize(function(){ responsiveSquares(); });
</script>
</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.