Román Cortés

Custom borders with CSS 2.1

1 de Febrero del 2010

Adding custom image-based borders for block elements with CSS 1 is painful. It usually requires adding a lot of extra markup that hurts semantics.

By other hand, with CSS 3, we have the powerful border-image property, wich allow us to add image-based borders easily, without extra markup and with new visual effects difficult to do with older CSS levels. Unfortunately, CSS 3 is being in development, not all browsers support it, and there is a long way to go until it gets mainstream.

The CSS 2.1 way to do it

I’ve search for middle way to do custom borders without the problem of adding extra markup of CSS 1, and more compatible than with CSS 3 properties. It is possible with CSS 2.1.

Pull-quote example

By using the CSS 2.1 pseudo classes :after and :before and setting their content property to an empty string (content: “”;), we can apply a lot of custom borders and background effects to block elements without additional markup. In the example above, I’ve done a pull-quote from a single <blockquote> element, that adapts to its inside text height.

So, what are the advantages of this method instead of using CSS3?

- Increased compatibility (it works even in IE8).
- Using a W3C recommendation - CSS 2.1 - instead of a working draft - CSS3 module border - makes no need for repeating properties in the CSS code for each browser (prefixes -moz, -o, -webkit, and so on).
- It is going to be completely mainstream a lot of time before CSS3 will be, so it looks as a more reasonable thing to learn today than the new CSS 3 properties if you are into real life web developing.

And… what are the disadvantages?

- More difficult to understand than the simple CSS 3 border-image property
- For round corners, you can probably do up to 3 of the 4 corners rounded for width and height resizable block elements… but not all the 4
- If you want all the corners with your custom images without adding markup, you will have a width-only resizable block element (looks as a good option for buttons) or an height-only resizable block element (like in my example).
- If you use CSS sprites like I did in my example, so you need only one image for the background, then you will be limited in resizing by the height or width of the image. You can always do very long images just as I did in my example.
- If you don’t use CSS sprites, you will need more than one image to load, and this is a disadvantage since CSS 3 border-image can work with a single image.

In next posts, I will probably follow the trend of showing cool effects and practical uses of CSS 3, but with this post I really want to remember you that there are a lot of possibilities with older CSS levels, and that it is really worth to continue studying them and experimenting with them.

4 Comentarios RSS