Search code examples
cssflexboxheightscrollbarviewport

Auto grow/shrink of divs to the mobile screen height


I'm wondering if it's possible to get rid of vertical scroll having 3 rows viewing on a mobile device that should fit/stretch to the height of screen's and shrink when the screen height is smaller than it should be, so if there's a taller device all elements would grow proportionally to fit the whole screen's height instead of having the scrollbar that appears every time when the sum of height of the container's elements is bigger than the screen's height. What properties should I use? Thank you.


Solution

  • You can do it with CSS Flexbox. I am posting an example that I believe creates the effect you want.

    In the HTML there are three rows (header, main, footer) wrapped inside a div:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
     <meta charset="UTF-8">
    </head>
        <body>
            <div>
                <header>
                    <p>Header</p>
                </header>
                <main>
                    <p>Main</p>
                </main>
                <footer>
                    <p>Footer</p>
                </footer>
            </div>
        </body>
    </html>
    

    and the CSS:

    html, body {
        margin: 0;
        padding: 0;
    }
    div {
        display: flex;
        flex-flow: column nowrap;
        height: 100vh;
    }
    
    header {
        background-color: lightblue;
        flex: 1 1;
    }
    
    main {
        background-color: lightcyan;
        flex: 1 1;
    }
    
    footer {
        background-color: lightgreen;
        flex: 1 1;
    }