Atrotygma
Atrotygma

Reputation: 1153

Dynamic split/row (by percentage) layout with CSS

I'm wondering if it's possible to have a multi-column split layout where every floating div has a dynamic width of 100%/n.

So if I have the following structure

<div id="mycontainer">
    <div class="split">
        LOREM
    </div>
    <div class="split">
        IPSUM
    </div>
</div>

the resulting css would be something like:

.split {
    float: left;
    width: 50%;
}

.split:last-child {
    float: right;
}

where as

<div id="mycontainer">
    <div class="split">
        LOREM
    </div>
    <div class="split">
        IPSUM
    </div>
    <div class="split">
        DOLOR
    </div>
</div>

would result in

.split {
    float: left;
    width: 33.33%;
}

and so on. I prefer plain CSS solutions, I know it's easily achievable with jQuery javascript in general.

Upvotes: 1

Views: 1505

Answers (5)

Roko C. Buljan
Roko C. Buljan

Reputation: 206353

A pure CSS solution would be to fake our DIV into our dear table, but hey, why not! It's a valid solution.

http://jsbin.com/amequw/1/edit

#mycontainer{
  background:#eee;
  padding:10px 0;
  display:table;      /* Fake :) */
  width:100%;
}
.split{
  background:#eee;
  display:table-cell; /* Act! */
}

and here's a demo with one .split less:

http://jsbin.com/amequw/2/edit

Upvotes: 6

mrksbnch
mrksbnch

Reputation: 1842

You could just use different classes for twocolumn, threecolumn, fourcolumn etc. So your CSS would look like something like this:

.column { float: left; }
.column-right { /* Just in case */ }

.twocolumn .column { width: 50%; }
.threecolumn .column { width: 33%; } 
 /* ... */

And your HTML like

<div class="twocolumn">
     <div class="column column-left">Split</div>
     <div class="column column-right">Split</div>
</div>

or

<div class="threecolumn">
     <div class="column column-left">Split</div>
     <div class="column">Split</div>
     <div class="column column-right">Split</div>
</div>

Upvotes: 2

Liam Sorsby
Liam Sorsby

Reputation: 2982

try using javascript/jquery to count the number of splits

var numItems = $('.split').length;

var percentage = 100/numItems;

$(".split").css("width",percentage+"%");

i've not tested the code but maybe worth a go

Upvotes: -1

Dave Mackintosh
Dave Mackintosh

Reputation: 2796

Check out Flexible boxes Not sure how supported they are at the moment but this will do what you want or display: table

Upvotes: 1

Andr&#233; Dion
Andr&#233; Dion

Reputation: 21728

If you're after a pure CSS solution, then you probably want to use a grid setup such as Foundation's, which involves using a combination of predefined classes to layout your elements.

Upvotes: 0

Related Questions