Jessica
Jessica

Reputation: 9830

Set height based on width

I'm trying to set the li's height based its width. I used JQuery for that.

var width = $('li').width();
$('li').css('height', width + 'px');

The problem is, it's not working. It's not the same exact size.

JSFiddle

$(document).ready(function () {
	"use strict";
	
	var width = $('li').width();
	
	$('li').css({
		'height': width + 'px',
        'background-color': 'green',
	});
    
    $(window).resize(function(){
   		$('li').height(width);
	});
});
html, body {margin: 0; height: 100%}

div {
	height: 100%;
	display: flex;
	justify-content: center;
	align-items: center;
	overflow: auto;
}

ul {
	padding: 0;
	margin: auto;
	width: 70%;
	
	display: inline-flex;
	flex-flow: row wrap;
	justify-content: flex-start;
	align-items: flex-start;
	align-items: center;
	align-content: center;
}

li {
	list-style-type: none;
	border: 1px solid tomato;
	box-sizing: border-box;
	flex-basis: calc(100%/3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <ul>
    	<li>1</li>
        <li>2</li>
        <li>3</li>
	    <li>4</li>
    </ul>
</div>

Upvotes: 1

Views: 111

Answers (2)

gidim
gidim

Reputation: 2323

jquery width() rounds the value to an integer. To avoid that i'm using getBoundingClientRect() which support decimals.

Try this:

$(document).ready(function () {
    "use strict";

    var elem = $("li")
    var width = elem[0].getBoundingClientRect().width

    $('li').outerHeight(width);



});

Since you asked to resize when window size changes:

   $(window).resize(function(){
        var elem = $("li")
        var width = elem[0].getBoundingClientRect().width

        $('li').outerHeight(width);
    });

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167220

May be, this is a hack, but try this:

$(document).ready(function () {
    "use strict";

    var width = $('li').width();

    $('li').css({
        'height': width,
        'width': width,
        'background-color': 'green'
    });
    $("li").height($("li").width());
    $("li").height($("li").width());

    $(window).resize(function () {
        var width = $('li').width();        
        $('li').css({
            'height': width,
            'width': width,
            'background-color': 'green'
        });
        $("li").height($("li").width());
        $("li").height($("li").width());
    });
});

Fiddle: http://jsfiddle.net/pu5xomhc/1/

Upvotes: 1

Related Questions