I’m trying to create a horizontal 100% stacked bar graph using HTML and CSS. I’d like to create the bars using DIVs with background colors and percentage widths depending on the values I want to graph. I also want to have a grid lines to mark an arbitrary position along the graph.
In my experimentation, I’ve already gotten the bars to stack horizontally by assigning the CSS property float: left. However, I’d like to avoid that, as it really seems to mess with the layout in confusing ways. Also, the grid lines don’t seem to work very well when the bars are floated.
I think that CSS positioning should be able to handle this, but I don’t yet know how to do it. I want to be able to specify the position of several elements relative to the top-left corner of their container. I run into this sort of issue regularly (even outside of this particular graph project), so I’d like a method that’s:
- Cross-browser (ideally without too many browser hacks)
- Runs in Quirks mode
- As clear/clean as possible, to facilitate customizations
- Done without JavaScript if possible.
You are right that CSS positioning is the way to go. Here’s a quick run down:
position: relativewill layout an element relative to itself. In other words, the elements is laid out in normal flow, then it is removed from normal flow and offset by whatever values you have specified (top, right, bottom, left). It’s important to note that because it’s removed from flow, other elements around it will not shift with it (use negative margins instead if you want this behaviour).However, you’re most likely interested in
position: absolutewhich will position an element relative to a container. By default, the container is the browser window, but if a parent element either hasposition: relativeorposition: absoluteset on it, then it will act as the parent for positioning coordinates for its children.To demonstrate:
In that example, the top left corner of
#boxwould be 100px down and 50px left of the top left corner of#container. If#containerdid not haveposition: relativeset, the coordinates of#boxwould be relative to the top left corner of the browser view port.