Sunday, 18 January 2015

HTML data bars with div

The div element can be used to create simple data bars.

Let's start out with a table:

<table>
    <tr>
        <th>Name</th>
        <th>Sales</th>
    </tr>
    <tr>
        <td>Smith</td>
        <td>70</td>
    </tr>
    <tr>
        <td>John</td>
        <td>81</td>
    </tr>
</table>

A data bar is, at its essence, a rectangle. Of course HTML purists might argue that this method does not respect semantics, but I think I lean towards the pragmatic side.

So, really, all we need is a div and some text overlaid on top.

<table>
    <tr>
        <th>Name</th>
        <th style="width:100%">Sales</th>
    </tr>
    <tr>
        <td>John</td>
        <td>
            <div style="position:relative;height:1em;width:100%">
                <div style="width:70%;background-color:green;height:1em"></div>
                <div style="width:100%;position:absolute;top:0;text-align:center;font-size:0.7em;color:white">70</div>
            </div>
        </td>
    </tr>
    <tr>
        <td>Smith</td>
        <td style="width:100%">
            <div style="position:relative;height:1em;width:100%">
                <div style="width:81%;background-color:green;height:1em"></div>
                <div style="width:100%;position:absolute;top:0;text-align:center;font-size:0.7em;color:white">81</div>
            </div>
        </td>
    </tr>
</table>

This produces something to this effect:


Homework! Use a CSS to simplify the markup, and explore how to add more series to the data bar (like John-Sales-North: 40, John-Sales-South: 30).

No comments:

Post a Comment