Rayjax
Rayjax

Reputation: 7784

Fill page with rectangles based on their number

I want to display some divs in my page based on this behavior : enter image description here

Depending on the number of divs, they will take up the size of the page until there are 8 of them, then at 9+ they will keep their size and the page will become scrollable.

I thought about using flexboxes like this but couldn't achieve exactly the expected behavior.

So I started putting a class with JS called "one" if there is one element, "two" for two elements etc. and then with this css (LESS):

.container.one {
    div:nth-child(1) {
        width: 100%;
        height: 100%;
    }
}
.container.two {
    div:nth-child(1) {
        width: 100%;
        height: 75%;
    }
    div:nth-child(2) {
        width: 100%;
        height: 25%;
    }
}

etc. up to 8.

It works OK but any better Idea, more concise, would be welcome

Upvotes: 3

Views: 176

Answers (1)

misterManSam
misterManSam

Reputation: 24692

The divs fill from the bottom thanks to:

  • display: table on <body>

  • display: table-cell and vertical-align: bottom on <div class="wrap">

Test by adding and removing divs.

div:last-child:nth-child(odd) is the magic sauce to spread the last odd div 100%.

Have an example!

HTML

<div class="wrap">
    <div><div> 
    <-- ... -->
</div>

CSS

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
html,body {
    height: 100%;
}
body {
    display: table;
    width: 100%;
}
.wrap {
    display: table-cell;
    vertical-align: bottom;
    width: 100%;
    height: 100%;
}
.wrap div {
    border: solid 1px #CCC;
    float: left;
    width: 50%;
    height: 25%;
}
.wrap div:last-child:nth-child(odd) {
    width: 100%;
}

Upvotes: 1

Related Questions