Skip to main content

How to Add a Border in CSS

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

The border property draws a line around an element. Give it three things, a width, a style and a color, as in border: 2px solid #0f6cbd.

Syntax​

Syntax
<selector> {
border: <width> <style> <color>;
}
PartWhat it does
<width>How thick the line is, such as 2px.
<style>The kind of line, such as solid, dashed or dotted. Without it there's no border.
<color>The line's color, such as #0f6cbd.

MDN's border page says that for a border to be displayed, the style must be set, because it defaults to none.

The Example​

The example is two short notices. One rule draws a blue border around the one with the class note.

Step 1: Write the Code​

Create a file named index.html in a text editor, such as Visual Studio Code:

index.html, an HTML page with a style element holding a rule for the class note with a 2px solid 0f6cbd border, and two paragraphs, the second with the class note.

index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Border</title>
<style>
.note {
border: 2px solid #0f6cbd;
}
</style>
</head>
<body>
<p>The office opens at 9:00.</p>
<p class="note">Bring your badge.</p>
</body>
</html>

Step 2: Open It in a Browser​

Double-click index.html. It opens in your browser:

The page in Chromium: The office opens at 9:00., then Bring your badge. inside a thin blue rectangle that runs across the page.

The screenshot comes from Chromium 159, the open-source browser that Chrome is built on.

What Happened​

  • The note has a 2-pixel solid blue border, rgb(15, 108, 189), on all four sides.
  • The border runs across the whole page, because a paragraph is as wide as the page.
  • The border sits right against the text. There's no space inside it until you add padding.

Common Mistakes​

MistakeWhat happensDo this instead
Leaving out the style: border: 2px #0f6cbdNo border shows: the style stayed none, and the width became 0pxAdd a style, such as solid
Using border when only one side needs a lineAll four sides get oneUse border-bottom, border-top, border-left or border-right

Troubleshooting​

SymptomLikely causeFix
No border appearsThe style is missing, or the selector doesn't matchAdd solid, and check the selector
The text touches the borderThere's no paddingAdd padding

FAQ​

Does the order of the three values matter?​

No. border: solid #0f6cbd 2px gave the same 2-pixel solid blue border.

How do I put a border on one side only?​

Use the property for that side. border-bottom: 2px solid #0f6cbd drew a line under the paragraph and nowhere else.

How do I make a dashed border?​

Use dashed as the style: border: 2px dashed #0f6cbd.

Conclusion​

Give border a width, a style and a color, in any order, and never leave out the style. Use the side properties, such as border-bottom, for a line on one side.

Additional Resources​