Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split bar chart using CSS

Tags:

html

css

I'm trying to create a split bar chart, using CSS. What I mean by this is something like this...

   _____       __________
 __|____| Text |_________|
|_______| Text |___|__
 |______| Text |______|

(Please excuse the crude drawing! I hope it makes sense)

Anyway, the code I have so far creates what I've attached on this JSFiddle

HTML:

<dl style="width: 600px">
<dt>2008</dt>
<dd><div id="data-one" class="bar" style="width: 5%">&nbsp;</div></dd>
<dt>2009</dt>
<dd><div id="data-two" class="bar" style="width: 80%">&nbsp;</div></dd>
<dt>2010</dt>
<dd><div id="data-three" class="bar" style="width: 64%">&nbsp;</div></dd>
<dt>2011</dt>
<dd><div id="data-four" class="bar" style="width: 30%">&nbsp;</div></dd>
<dt>2012</dt>
<dd><div id="data-five" class="bar" style="width: 30%">&nbsp;</div></dd>
<dt>2013</dt>
<dd><div id="data-six" class="bar" style="width: 30%">&nbsp;</div></dd>
</dl>

CSS:

dt { 
    float: left; padding: 4px; 
}

.bar {
    margin-bottom: 10px;
    color: #fff;
    padding: 4px;
    text-align: center;
    background-color: #FFC94D;
    -webkit-border-radius: 2px;
    -moz-border-radius: 2px;
    border-radius: 2px;
}

I've been playing around with this for hours, but cannot work out how best to put a second bar on the left of the central column of text. The closest I got was getting the two bars on top of each other?! I assume there is a better way of doing this, but I honestly haven't got a clue. Does anybody have a possible solution?

Many thanks, Dave

like image 498
David Lettice Avatar asked Oct 01 '22 15:10

David Lettice


1 Answers

Sticking with the description list (<dl>, <dt>, <dd>) makes this a little hard without breaking the HTML flow, but I think I've found a way that works and is mostly fluid.


First, add your second bars as additional <dd> elements, thereby maintaining proper HTML structure:

<dt>2008</dt>
<dd>
    <div id="data-one-left" class="bar" style="width:10%">&nbsp;</div>
</dd>
<dd>
    <div id="data-one-right" class="bar" style="width: 5%">&nbsp;</div>
</dd>

Next, center your <dt> elements and give them a fluid width and height:

dl {
    width: 100%;
}
dt {
    height: 2rem;
    width: 8%;
    margin: 0 auto;
    text-align: center;
    line-height: 2rem;
}

Now give your <dd> elements the remaining width and float them left/right:

dd {
    width: 46%;
    margin: -2rem;
}
dd:nth-of-type(odd),
dd:nth-of-type(even) div {
    float: left;
}
dd:nth-of-type(even),
dd:nth-of-type(odd) div {
    float: right;
}

Here a working jsfiddle.


The one thing I do not like about this solution, is that I had to give the <dd> elements a negative top margin equal to the height of the <dt> elements in order to align things. Maybe someone else can come up with a better way of handling this... I couldn't think of anything.

like image 157
pschueller Avatar answered Oct 05 '22 11:10

pschueller