Archive for May, 2009

Generating double borders with CSS04
May

I was working on a site the other day which had double borders around images. This is nothing new and is easily achievable with no extra markup and a bit of basic CSS. The problems arose when I wanted to achieve the same effect using a div.

Let’s start with the image example…

img {
background:#222;
padding:3px;
border:3px solid #666;
}

This gives us the following effect…

Baby red howler monkey which I photographed on the Tambopata river in Peru.

I then wanted to achieve the same effect with a div. The most obvious option was to use two divs and put one border on each div.


#innerDiv{
background:#fff;
border:3px solid #222;
padding:8px;
}
#outerDiv{
border:3px solid #666;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi ultrices dignissim neque. Suspendisse potenti.

Although this worked I was not keen on using an extra div purely for presentational purposes and decided to work on a more css-based solution. I refreshed my knowledge of the CSS border property and then came up with the idea of combining border-style:ridge and border-style:groove to make a two-tone double border.


#myDiv1{
background:#fff;
padding:8px;
border-top:6px ridge #444;
border-right:6px groove #444;
border-bottom:6px groove #444;
border-left:6px ridge #444;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi ultrices dignissim neque. Suspendisse potenti.

This approach enabled me to get a double border only using one div but it still had it’s limitations. The groove and ridge border styles spilt the border in half so for this example 3px and 3px it worked fine. However if I had wanted to make one border thicker than the other this would not have been possible. Also you only get to define a starting colour for the border, in this example #444. The browser then uses this to generate a lighter (#c6c6c6) and darker (#262626) border. Not being able to specify border colours and border widths meant that this solution was not feasible.

Finally I tried using the css outline property. CSS outlines are similar to borders but they do not take up any room on the page. This means that they overlap other elements that are next to them in the page. To counter act this it is therefore also necessary to add some margin to our div.


#myDiv2{
background:#fff;
padding:8px;
border:3px solid #222;
outline:3px solid #666;
margin:3px;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Morbi ultrices dignissim neque. Suspendisse potenti.

This solution enables us to control the thicknesses and colours of each border independently and does not require any extra html markup. This was the option that I went with.

EDIT 28/05/09: Unfortunately (but not suprisingly) this last option does not work in Internet Explorer due to lack of support for the CSS outline property. Back to the drawing board.