Carl Papworth
Carl Papworth

Reputation: 1332

Making a jQuery-based square resize

So I have a , where each li is a square. Now the

  • width in the css is based on percentage of the , wanting it responsive. Hence I use a jQuery to get the same height as the width to make them square.

    However, on resize, only the width is affected, the height stays with it's original on-load-value. Anyways to get around this?

    Here's me code:

    Here's me code:

    html:

     <ul>
        <li class="square">item1</li>
        <li class="square">item1</li>
        <li class="square">item1</li>
        <li class="square">item1</li>
     </ul>
    

    Css:

    ul{
    width: 50%;
    height: auto;
    }
    
    li.square{
    width: 25%;
    float: left;
    }
    

    javascript:

    $(document).ready(function() {  
     var width = $('.square').width();
      $('.square').css('height', width);
    });
    

    Upvotes: 0

    Views: 610

  • Answers (1)

    James Donnelly
    James Donnelly

    Reputation: 128856

    JavaScript shouldn't be related to responsive design. If you want your design to be responsive you can make use of Media Queries or, depending on which browsers you wish to support, you could also make use of Viewport-Percentage Lengths.

    Viewport Percentage Lengths allow you, in CSS, to scale elements relative to the viewport. There are 4 associated units: vw (viewport width), vh (viewport height), vmin (the minimum screen length) and vmax (the maximum length). If you wish to make a square which scales, you can make use of vmin or vmax:

    .square {
        display:inline-block;   /* To override the list styling */
        height:20vmin;
        width:20vmin;
    }
    

    In specifying 20vmin, these li elements will now scale to 20% of the size of the minimum screen length. If your viewport's resolution was 1000x500 (1000px width, 500px height), 20vmin would be equal to 20% of the height (as the height is the smaller length).

    JSFiddle demo.

    Upvotes: 3

    Related Questions