How to Create Dashed Border in CSS: Simple Syntax & Examples
To create a dashed border in CSS, use the
border-style: dashed; property on an element. You can combine it with border-width and border-color to control the thickness and color of the dashed border.Syntax
The dashed border is created using the border-style property set to dashed. You usually combine it with border-width to set thickness and border-color to set the color.
- border-width: Thickness of the border (e.g., 2px)
- border-style: Type of border line (use
dashedfor dashed lines) - border-color: Color of the border (e.g., black, #000)
css
selector {
border-width: 2px;
border-style: dashed;
border-color: black;
}Example
This example shows a box with a black dashed border that is 3 pixels thick. The border is visible around the box.
css
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
}
.box {
width: 200px;
height: 100px;
border-width: 3px;
border-style: dashed;
border-color: black;
background-color: white;
display: flex;
justify-content: center;
align-items: center;
font-family: Arial, sans-serif;
font-size: 1rem;
color: #333;
}Output
<div class="box">Dashed Border Box</div>
Common Pitfalls
Common mistakes when creating dashed borders include:
- Forgetting to set
border-styletodashed, which results in no visible border. - Setting
border-widthto 0 or not setting it at all, so the border is invisible. - Using shorthand
borderproperty incorrectly, which can override the dashed style.
Example of wrong and right usage:
css
/* Wrong: border-style missing, no visible border */ .wrong { border-width: 2px; border-color: red; } /* Right: border-style set to dashed */ .right { border-width: 2px; border-style: dashed; border-color: red; }
Quick Reference
Summary tips for dashed borders:
- Always set
border-style: dashed;to see the dashed effect. - Use
border-widthto control thickness. - Use
border-colorto change the border color. - You can use shorthand like
border: 2px dashed blue;for convenience.
Key Takeaways
Use
border-style: dashed; to create a dashed border in CSS.Combine with
border-width and border-color to control thickness and color.Without
border-style, the border will not appear even if width and color are set.You can use shorthand
border property like border: 2px dashed black; for simplicity.Check your CSS carefully to avoid missing the
border-style property.