简体   繁体   中英

Dynamically resize div based on size of browser window

I'm trying to figure out how to have a div dynamically resize, based on the size of the browser window. I've set up a jsbin that illustrates my problem, here: http://jsbin.com/uxomul

What I want to do is to resize the div that holds the images so that the div always fills what's left of the height of the browser window (except a 25px margin at the bottom, that's set on body).

Here's a demo that maybe illustrates what I want to achieve more clearly: http://emilolsson.com/shop/demo/layers

Any ideas what would be the best way to approach this?

You can do something like this:

var width = $(window).width() - 25; 
$("#mydiv").width(width);

25 is just a sample number, for example your margin (you can get this dynamically too)

You may also want to wrap it into a function and call this on both page load and on resize

Use CSS position:absolute/relative in combination with CSS top/bottom/left/right. Example:

<!doctype html>
<html>
    <head>
        <style> 
            html, body    { margin:0; padding:0; width:100%; height:100%; }

            #head         { width:100%; height:100px; background:black; color:white; }
            #head > h1    { margin:0; }

            #body         { position:absolute; width:100%; top:100px; bottom:25px; background:red; }
            #body > div   { position:absolute !important; }
            #body-sidebar { width:200px; top:0; bottom:0; background:black; color:white; }
            #body-content { left:200px; right:0; top:0; bottom:0; background:white; overflow:scroll; }
            #body-content > img { margin:25px; width:500px; vertical-align:middle; }
        </style>
    </head>

    <body>

        <!-- Head -->
        <div id="head">
            <h1>Header</h1>
        </div>

        <!-- Body -->
        <div id="body">

            <!-- Sidebar -->
            <div id="body-sidebar">
                <h2>Sidebar</h2>
            </div>

            <!-- Content -->
            <div id="body-content">
                <h2>Content</h2>
                <img src="http://dl.dropbox.com/u/3618143/image1.jpg" />
                <img src="http://dl.dropbox.com/u/3618143/image2.jpg" />
                <img src="http://dl.dropbox.com/u/3618143/image3.jpg" />
            </div>

        </div>

    </body>
</html>

You can try to bind to the resize event of the browser's window.

For example:

window.onresize = function() {
//your code
}

Position must be fixed so it will be resized automatically.

If screen height changed in run time

Put this in CSS sheet:

#FitScreenHeight
{
    position:fixed
    height:100%
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM