CSS Outline
The CSS outline property is used to set a line around an element, outside the border. Unlike borders, outlines do not take up space and are not affected by padding or margin. They are commonly used for accessibility (e.g., focus indicators) and styling elements with emphasis.
Key Points on CSS Outline:
- The
outline
property is a shorthand for settingoutline-width
,outline-style
, andoutline-color
in a single declaration. - Outlines do not affect the layout of the element, unlike borders, as they are drawn outside the element's box.
- Outlines can be used for accessibility, such as highlighting the focused element on the page.
- By default, outlines are used to indicate keyboard navigation (focus) in elements like buttons and input fields.
- Outlines can be customized with different styles, such as solid, dotted, dashed, etc.
Syntax for CSS Outline:
Syntax Example
/* Outline shorthand syntax */
outline: width style color;
/* Example */
outline: 2px solid red;
Examples of CSS Outline:
The following examples demonstrate how to use different outline properties:
Code Example: Outline
div {
outline: 3px dashed blue;
}
Output
This div has a blue dashed outline.
Code Example: Outline Color
div {
outline-color: green;
}
Output
This div has a green outline.
Common Outline Properties:
- outline-width: Sets the width of the outline. It can take values like
thin
,medium
,thick
, or specific pixel values (e.g.,2px
). - outline-style: Sets the style of the outline. Possible values include
solid
,dashed
,dotted
,double
, etc. - outline-color: Defines the color of the outline. You can use color names, hex, rgb, rgba, or any other valid color value.
- outline-offset: Specifies the space between the outline and the edge of the element's border box.
To make the outline more accessible, ensure it is visible and clearly distinct when focusing on elements. Outlines should not be removed entirely for interactive elements like links and form inputs to support keyboard navigation.