Three-Sided Border

Avatar of Chris Coyier
Chris Coyier on

If you need to put a border on only three sides of an element, there are a bunch of ways you can do it.

You can specifically declare the border on just three sides:

div { 
  border-top:    1px solid red;
  border-right:  1px solid red; 
  border-bottom: 1px solid red;
}

Verbose, but easy to understand.

Or, you could declare just a border which will cover all four sides and remove the one you don’t want.

div {
  border: 1px solid red;
  border-left: 0;
}

Much shorter, but relies on understanding and maintaining that the border removing override is kept after the border declaration.

Or, you could declare the color and styling and use shorthand only the border-width to specifically declare the three sides.

div {
  border-color: red;
  border-style: solid;
  border-width: 1px 1px 1px 0;
}

Shorter than the first example, but less repeative. Just need to be aware if left border did acquire width it would already be red and solid.

And then there is the fact that borders affect the size of the element under the regular box model. If you wanted to add borders without adding to the size of the element, you’ll need to lean on CSS3. Here is a way to do it with inset shadows:

div {
  -webkit-box-shadow:
     inset -1px 0   0 red,
     inset  0  -1px 0 red,
     inset  0   1px 0 red;
  -moz-box-shadow:
     inset -1px 0   0 red,
     inset  0  -1px 0 red,
     inset  0   1px 0 red;
  box-shadow:
     inset -1px 0   0 red,
     inset  0  -1px 0 red,
     inset  0   1px 0 red;
}

But then inset box shadows has far less browser support than borders do. For example, the code above will only work in Internet Explorer version 9+. If you’d rather use borders, and still not affect the elements size, you could play with box-sizing, which is supported down to IE 8.

Oh the choices! This is such a small thing, but I think it is a good example of how there is so often many different ways to accomplish the same thing in CSS. If you are just starting out in CSS, is this kind of thing confusing or pretty straightforward?

See all examples.