In this post I'd like to explain how to create a pure CSS bar chart. To accomplish this task, we need some data to show. In our example, we'll show the statistics of the 3 most used browser at the moment, namely Internet Explorer, Firefox and Chrome. On the top of each bar, we also want to include an icon for each browser. Let's start with our basic markup:
<div id="chart"> <div id="ie"><span>45%</span></div> <div id="ff"><span>30%</span></div> <div id="chrome"><span>25%</span></div> </div>
As you can see, each bar contains a different percentage. This is important, because we want our chart to contain actual data in order to avoid the use of empty elements. To create our bar chart, we first need to position the main container in the center of the viewport. This can be accomplished using absolute positioning:
#chart { width: 600px; height: 500px; margin: -250px 0 0 -300px; font: 100% Arial, sans-serif; position: absolute; top: 50%; left: 50%; border-left: 1px solid #333; border-bottom: 1px solid #333; }
The left and bottom border of our container will actually draw the y and x axes, respectively. Since our container has been absolutely positioned, a new contextual positioning has been created for its child elements. We can take advantage of this fact and absolutely position our bars as well:
#ie { position: absolute; width: 120px; height: 100%; background: #fff url(ie.jpeg) no-repeat 0 0; left: 20px; bottom: 0; font-weight: bold; font-size: 1.5em; } #ie span { display: block; width: 100%; height: 400px; background: #008; color: #fff; text-align: center; line-height: 400px; position: absolute; bottom: 0; left: 0; } #ff { position: absolute; width: 120px; height: 100%; background: #fff url(firefox.jpg) no-repeat 0 80px; left: 160px; bottom: 0; font-weight: bold; font-size: 1.5em; } #ff span { display: block; width: 100%; height: 300px; background: #a00; color: #fff; text-align: center; line-height: 300px; position: absolute; bottom: 0; left: 0; } #chrome { position: absolute; width: 120px; height: 100%; background: #fff url(chrome.jpg) no-repeat 0 130px; left: 300px; bottom: 0; font-weight: bold; font-size: 1.5em; } #chrome span { display: block; width: 100%; height: 250px; background: #080; color: #fff; text-align: center; line-height: 250px; position: absolute; bottom: 0; left: 0; }
Each bar has a different ID and has been positioned at the bottom of the main container. To display the level of each bar, we use a span
element with a different background color, also positioned at the bottom of its parent container. Further, each bar has a different left offset, calculated by summing up the width of the bar (120 pixels) and adding an additional 20 pixels. Finally, each bar has a different background image that has been vertically positioned with a different offset. You can see a demo below.