Mesign
Mesign

Reputation: 101

Float div elements beneath eachother

I want to have the div elements beneath each other. So 1, 2 and 3 are OK, 4 beneath 3.

Image: http://img42.com/DZIeu+

The HTML has to be the same because a user can add a new div. (max of 8 div's, so the oldest div goes away). Because of the browser support of nth I don't want to use Absolute positioning or fixed width.

HTML:

<div id="wrapper">
<div id="nwsgal">
    <div class="nwsitem">1</div>
    <div class="nwsitem">2</div>
    <div class="nwsitem">3</div>
    <div class="nwsitem">4</div>    
    <div class="nwsitem">5</div>
    <div class="nwsitem">6</div>
    <div class="nwsitem">7</div>
    <div class="nwsitem">8</div>
</div>

CSS:

#nwsgal{
background:#FAFAFA;
width:100%;
height:40%;
min-height:250px;
display:block;
position:relative;  
overflow:hidden;
vertical-align:top;
}

.nwsitem{
    background:#999;
    width:25%;
    height:100%;
    display:block;
    position:relative;
    float:left;
}

.nwsitem:nth-child(3), .nwsitem:nth-child(4){width:25%; height:50%;}
.nwsitem:nth-child(5), .nwsitem:nth-child(6), .nwsitem:nth-child(7), .nwsitem:nth-child(8){width:12.5%; height:50%;}
.nwsitem:nth-child(odd){background:#FDFDFD;}

http://jsfiddle.net/ntxhbj43/

Any ideas, js/css solution?

Upvotes: 1

Views: 115

Answers (1)

giorgio
giorgio

Reputation: 10202

Wrap them in a container.

<div id="wrapper">
    <div id="nwsgal">
        <div class="nwsitem">1</div>
        <div class="nwsitem">2</div>
        <div class="nwsitemwrap">
            <div class="nwsitem">3</div>
            <div class="nwsitem">4</div>    
        </div>
        <div class="nwsitemwrap">
            <div class="nwsitem">5</div>
            <div class="nwsitem">6</div>
        </div>
        <div class="nwsitemwrap">
            <div class="nwsitem">7</div>
            <div class="nwsitem">8</div>
        </div>
    </div>
</div>

Need a bit of additional styling for the wrappers and children of the wrappers:

.nwsitemwrap { float: left; width: 25%; }
.nwsitemwrap > .nwsitem { width: 100%; float: none; }

EDIT And here's a functional fiddle. To make it "dynamic" we'd need to know how you want to layout the items on certain cases.

Upvotes: 2

Related Questions