Search code examples
cssaspect-ratiosizing

Can I set the height of a div based on a percentage-based width?


Let's say I've got a div that has a width of 50% of the body. How do I make its height equal to that value? So that when the browser window is 1000px wide, the div's height and width are both 500px.


Solution

  • This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.

    Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:

    $(function() {
        var div = $('#dynamicheight');
        var width = div.width();
        
        div.css('height', width);
    });
    #dynamicheight
    {
        width: 50%;
        
        /* Just for looks: */
        background-color: cornflowerblue;
        margin: 25px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <div id="dynamicheight"></div>

    If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):

    $(window).ready(updateHeight);
    $(window).resize(updateHeight);
    
    function updateHeight()
    {
        var div = $('#dynamicheight');
        var width = div.width();
        
        div.css('height', width);
    }
    #dynamicheight
    {
        width: 50%;
        
        /* Just for looks: */
        background-color: cornflowerblue;
        margin: 25px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    
    <div id="dynamicheight"></div>