How to add and style a horizontal line in HTML (beginner’s guide)
How to add and style a horizontal line in HTML (beginner’s guide)
Ever wondered how to visually break up content on a webpage or separate sections neatly? That’s where horizontal lines come in. They’re simple yet powerful tools for improving readability and layout flow.
This guide will show you everything you need to know — from using the basic <hr> tag to styling it beautifully with CSS.
Understanding the <hr> tag
At the core of adding a horizontal line is the <hr> tag, short for “horizontal rule.” It’s self-closing (no </hr> needed) and represents a thematic break between sections.
Example:
<p>This is content before the line.</p>
<hr>
<p>This is content after the line.</p>
By default, it appears as a thin gray line — clean but plain. That’s where CSS styling comes in.
From old HTML to modern CSS
In older HTML, people used:
<hr width="50%" size="3" color="red">
These attributes are now deprecated in HTML5.
The modern way is to use CSS, separating structure (HTML) from presentation (CSS).
Styling horizontal lines with CSS
You can target all <hr> elements or specific ones with a class:
hr {
/* styles here */
}
hr.custom-line {
/* custom styles */
}
Basic CSS properties
-
colororbackground-color— sets line color -
height— makes the line thicker -
width— controls length -
border— remove or style the border -
margin— adds spacing above and below
Example:
<p>Content above.</p>
<hr class="styled-line">
<p>Content below.</p>
.styled-line {
border: none;
height: 2px;
background-color: #3498db;
width: 70%;
margin: 40px auto;
}
Advanced styling
Dashed line
.dashed-line {
border: none;
border-top: 2px dashed #e74c3c;
width: 80%;
margin: 30px auto;
}
Gradient line
.gradient-line {
border: none;
height: 3px;
background-image: linear-gradient(to right, #f39c12, #e67e22, #f1c40f);
width: 90%;
margin: 50px auto;
}
Shadow effect
.shadow-line {
border: none;
height: 1px;
background-color: #bdc3c7;
box-shadow: 0 5px 5px -5px #333;
width: 60%;
margin: 60px auto;
}
Best practices
-
Use meaningfully: Each line should mark a clear content break.
-
Stay consistent: Use the same style throughout your site.
-
Ensure contrast: Lines should be visible against the background.
-
Be responsive: Use percentages for width so they adapt to screen sizes.
-
Avoid clutter: Too many lines can distract the reader.
Common mistakes
-
Using deprecated HTML attributes (
width,size,color) -
Replacing
<hr>withdivborders — you lose semantic meaning -
Forgetting to reset browser defaults (use
border: none;)
Conclusion
Knowing how to add and style a horizontal line in HTML is a small but powerful skill. The <hr> tag provides both structure and meaning, while CSS gives you design flexibility.
Use it wisely to create clean, readable, and visually appealing layouts that guide your reader smoothly through your content.
Post a Comment