Gautam Kumar
Gautam Kumar

Reputation: 983

Square containers in html using jquery and css

I want to create a class named square when assigned to particular container should have width equal to its height. The layout should be responsive.

My current implementation:

$('.square').height($('.square').width());
$( window ).on("resize",function() {
    $('.square').height($('.square').width());
});

This buggy code take width of first element and assign all the square classes same height.

How can i implement this correctly using jquery and css?

Upvotes: 1

Views: 232

Answers (2)

Jordan Burnett
Jordan Burnett

Reputation: 1844

Before you implement a Javascript solution it's possible to do this with pure CSS.

If you give the padding-top property of an element a percentage value, it is relative to the width of it's parent. Using pseudo elements we can create an extra container that is always as tall as it's parent is wide, making it square.

.square {
    width: 200px;
    position: relative
}
.square:after {
    content: "";
    display: block;
    width: 100%;
    padding-top: 100%;
}

Example here: http://jsfiddle.net/kexxv1jh/

If you don't need any text in the container, you can drop the whole inner div altogether

Upvotes: 0

Satpal
Satpal

Reputation: 133403

You can use .height(function)

Within the function, this refers to the current element in the set.

Code

$( window ).on("resize",function() {
    $('.square').height(function() {
       return $(this).width();
    });
});

Upvotes: 1

Related Questions