PrimitiveType

How to set and style borders with CSS


In this brief article, I look at how CSS can be used to add borders to the elements of your webpage.

The easiest way to set a border for an element is to use the CSS border property, with which you can set the style, width and colour of all sides of a border in one declaration. The border property takes three parameters: width, style and colour.

The style parameter can be any of these values:

  • none
  • hidden
  • dotted
  • dashed
  • solid
  • double
  • groove
  • ridge
  • inset
  • outset

The following declaration sets a border to be 1 pixel thick, dotted and red:

border:1px dotted #FF0000;

As with all CSS properties, you can set the border in the style attribute of an element, the style tag in the document header, or in a separate stylesheet linked to from within the page. In the examples below, each border is blue and 4 pixels wide. Each border declaration is applied to the style attribute of a paragraph tag (<p>) and is repeated inside the paragraph so you can see it.

border:4px solid #0000FF;

border:4px dotted #0000FF;

border:4px dashed #0000FF;

border:4px double #0000FF;

border:4px groove #0000FF;

border:4px ridge #0000FF;

border:4px inset #0000FF;

border:4px outset #0000FF;

You can set the borders for each side of an element individually. That is, you can set the top, bottom, left and right borders separately, using the property names border-top, border-bottom, border-left and border-right:

border-top:4px solid #0000FF;border-bottom:4px dotted #FF0000;border-left:4px dashed #00FF00;border-right:4px inset #00FF00;

As can be seen above, CSS offers fine grained control over the properties of a border. The properties above can be seen as shorthand declarations as with CSS you can set, for example, the border-left-color or the border-bottom-style of an element. These individual properties are probably most useful when you want to override just one aspect of a border set, for instance, in a CSS class.

You will often see borders with rounded edges on websites. These are not easy to achieve with just CSS, although it is doable. Usually, rounded borders consist of images slotted into the HTML such that they blend with the straight border portions of an element set with CSS. For a handy example, see the navigation menu to the left of every page on this site.