CSS-only square div fitting inside rectangle div

前端 未结 4 645
忘掉有多难
忘掉有多难 2021-01-06 02:54

I have determined how to set a div height based on its width (using percentage width and padding-bottom). But I also need to be able to set a div width based on its height.

4条回答
  •  心在旅途
    2021-01-06 03:20

    You could try using jquery to listen for the resize events. Check out the this JSFiddle.

    $(".screen").resizable({});
    
    $(".screen").on("load resize",function(e){
        var rectangle = $(".rectangle");
        var square = $(".square");
        
        var rectWidth = rectangle.width();
        var rectHeight = rectangle.height();
        if(rectWidth < rectHeight){
        	square.width(rectWidth);
            square.height(rectWidth);
        }
        else{
        	square.width(rectHeight);
            square.height(rectHeight);
        }
    });
    .screen{
        background: gray;
        width: 100px;
        height: 100px;
    }
    
    .rectangle{
        background: blue;
        width: 90%;
        height: 90%;
    }
    
    .square{
        background: red;
        width: 30px;
        height: 30px;
    }

    It includes JQueryUI only to simulate the resizing of the "screen".

提交回复
热议问题