0
0
CssHow-ToBeginner · 3 min read

How to Set Border in CSS: Simple Syntax and Examples

To set a border in CSS, use the border property with values for width, style, and color, like border: 2px solid black;. This adds a visible line around an element. You can also set each side's border separately using border-top, border-right, border-bottom, and border-left.
📐

Syntax

The border property in CSS combines three parts:

  • Width: How thick the border line is (e.g., 1px, 3px).
  • Style: The type of border line (e.g., solid, dashed, dotted).
  • Color: The color of the border (e.g., black, #ff0000).

You can write them together like this:

css
selector {
  border: <width> <style> <color>;
}
💻

Example

This example shows a box with a 3-pixel thick solid blue border. It demonstrates how the border property adds a visible line around an element.

css
div {
  width: 200px;
  height: 100px;
  border: 3px solid blue;
  padding: 10px;
  margin: 20px;
}
Output
A rectangular box 200px wide and 100px tall with a solid blue border around it.
⚠️

Common Pitfalls

Some common mistakes when setting borders in CSS include:

  • Forgetting to specify the style (like solid), which makes the border invisible.
  • Using invalid values for width or color.
  • Setting border properties on inline elements without changing their display, so the border may not show as expected.

Here is an example showing the wrong and right way:

css
/* Wrong: No style specified, border won't show */
div.wrong {
  border: 2px red;
}

/* Right: Style included, border visible */
div.right {
  border: 2px solid red;
}
Output
The first box has no visible border; the second box has a 2px solid red border.
📊

Quick Reference

PropertyDescriptionExample Value
border-widthSets thickness of border2px, 0.1rem
border-styleSets border line stylesolid, dashed, dotted, none
border-colorSets border colorblack, #00ff00, rgba(0,0,0,0.5)
border-topSets top border3px solid blue
border-rightSets right border1px dashed red
border-bottomSets bottom border4px dotted green
border-leftSets left border2px solid black

Key Takeaways

Always include border style (like solid) to make the border visible.
Use the shorthand border property to set width, style, and color in one line.
You can set borders on each side separately for more control.
Borders don’t show on inline elements unless their display is changed.
Use valid CSS units and color formats for consistent results.