Search code examples
htmlcssflexboxmarkup

Flex-box: 3 columns of same height with page scroll


I am new to Flexbox and I am working on a 3-column layout.

This is what I am targeting:

  • 3 columns
  • Each 100% height
  • Variable content height in each
  • If content is taller than user's screen the page should scroll
  • Columns should stay the same height

enter image description here

This is my HTML code:

<html>
    <head>
        <title>
            FlexBox
        </title>
        <link rel="stylesheet" href="./styles.css">
    </head>
    <body>
        <div class="container">
            <div class="cols">
                1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>
                1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>
                1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>
                1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>
                1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>
                1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>1<br>
            </div>
            <div class="cols">
                text
            </div>
            <div class="cols">
                text
            </div>
        </div>
    </body>
</html>

and CSS:

body, html {
    background-color: seashell;
    margin: 0;
}

.container {
    display: flex;
    justify-content: center;
    height: 100%;
}

.container .cols {
    flex: 1 0 auto;
    background-color: burlywood;
    margin: 10px 10px 0 10px;
    padding: 10px;
}

What happens in this case is content overflows the column (that gets 100% of screen height):

enter image description here

What I have tried to fix it:

  1. Remove height: 100% from .container: It leads to right look when content is tall and stretches the column, but if the content is small - columns will not be 100% screen height. So it does not work for me.

  2. Adding align-items: flex-start to .container: So now content stretches the column but, again, if content is small none of columns 100% screen height.

How can I fix it?

PS: Strange thing, when I tried this example in jsfiddle it works as expected but when I run it in my browser - i get what's described above.

Thanks!


Solution

  • Change height:100% to min-height:100% of .container, also add height:100% to body, html

    .container {
        display: flex;
        justify-content: center;
        min-height: 100%;
    }
    
    body, html {
        background-color: seashell;
        margin: 0;
        height: 100%
    }