Add vertical dividers with CSS


This is a little snippet of how one adds a vertical line that is the same height to columns that isn't by using CSS.

Lets say that you have a menu consisting of several columns, something like this:
<style>
.first-column,
.column {
float:left;
width:200px;
}
.column {
margin-left:30px;
}
</style>

<div id="fat-menu">
<div class="first-column">
..content..
</div>
<div class="column">
..content..
</div>
<div class="column">
..content..
</div>
<div style="clear:both;"></div>
</div>

And you would like to add vertical lines as dividers between each column. But using a border-left on all but the first column would not do it since the columns contains different amount of data and therefor are of different heights.

Another solution would be to use CSS in order to add those lines and make them the same height of it's container, thereby following the highest column.

This can be achieved by using the :before rule in CSS that injects elements before the matching element, in our case .column.

Besides adding a new :before rule we need to make sure that any offset given using top and bottom attributes are relative to it's parent and not the window (or other grand parent). This is done by setting position to relative on the menu container.

We use the margin in order to position the line 15 pixels to the left of the column.
<style>
#fat-menu {
/* Set position so that offsets in children are based on parent */
position: relative;
}

.first-column,
.column {
float:left;
width:200px;
}

.column {
margin-left:30px;
}

.column:before {
content:" ";
margin:0 -15px;
position: absolute;
top: 0;
bottom: 0;
width: 1px;
background: #666666;
}
</style>

<div id="fat-menu">
<div class="first-column">
..content..
</div>
<div class="column">
..content..
</div>
<div class="column">
..content..
</div>
<div style="clear:both;"></div>
</div>

Done! Adjust the top, bottom, background and margin attributes accordingly to your requirements.


Related posts:

Comments

comments powered by Disqus