How to Use Outline in CSS: Syntax, Examples, and Tips
Use the
outline property in CSS to draw a line around an element outside its border without affecting layout. It accepts values for outline-width, outline-style, and outline-color to customize the outline's thickness, pattern, and color.Syntax
The outline property is a shorthand to set the width, style, and color of an outline around an element. It does not take up space and does not affect the element's size or position.
- outline-width: thickness of the outline (e.g.,
2px) - outline-style: pattern of the outline (e.g.,
solid,dashed,dotted) - outline-color: color of the outline (e.g.,
red,#000)
css
outline: <outline-width> <outline-style> <outline-color>;
Example
This example shows a blue solid outline around a button. The outline is 3 pixels thick and does not change the button's size or position.
css
button {
outline: 3px solid blue;
padding: 10px 20px;
font-size: 1rem;
cursor: pointer;
}
button:focus {
outline: 3px dashed orange;
}Output
A button with a blue solid outline around it. When focused (clicked or tabbed to), the outline changes to orange dashed.
Common Pitfalls
Many beginners confuse outline with border. Unlike borders, outlines do not take up space and do not affect layout. Also, outlines can be invisible if outline-style is not set or set to none. Another common mistake is relying on outlines for design only; outlines are mainly for accessibility focus indication.
css
/* Wrong: outline-style missing, outline won't show */ div { outline: 2px red; } /* Correct: outline-style added */ div { outline: 2px solid red; }
Quick Reference
| Property | Description | Example Values |
|---|---|---|
| outline-width | Thickness of the outline | thin, medium, thick, 2px |
| outline-style | Pattern of the outline | none, solid, dashed, dotted, double |
| outline-color | Color of the outline | red, #00f, rgba(0,0,0,0.5) |
| outline-offset | Space between outline and element border | 0, 5px, -2px |
Key Takeaways
The CSS
outline draws a line outside an element without affecting layout.Always specify
outline-style for the outline to be visible.Use
outline mainly for accessibility focus indication, not decoration.Outline can be customized with width, style, color, and offset.
Outline differs from border because it does not take up space or change element size.