In HTML, the <hr> element is used to denote a topic separator or a break between paragraphs within a thematic section. By default, the <hr> element appears as a horizontal line, and its appearance can be customized using CSS, including changing the color.
To change the color of the <hr> element, you can apply CSS styles to it. There are several methods to achieve this:
Using Inline Styles
You can directly set the color by using the style attribute within the <hr> tag:
html<hr style="border: none; height: 2px; background-color: #ff0000;" />
In this example, we set the <hr>'s border property to none to remove the default border, height to define the line thickness, and background-color to set the color to red (#ff0000).
Using Internal or External CSS
You can also define CSS rules in the <head> section of the HTML document using the <style> tag, or in an external CSS file linked to the HTML document.
Internal Styles
In the <head> section of the HTML document:
html<style> hr.customHr { border: none; height: 2px; background-color: #ff0000; /* red */ } </style>
Then apply this class in the HTML body:
html<hr class="customHr" />
External Styles
In an external .css file:
css.customHr { border: none; height: 2px; background-color: #ff0000; /* red */ }
Link this CSS file in the HTML document:
html<link rel="stylesheet" type="text/css" href="styles.css" />
Then apply this class in the HTML body:
html<hr class="customHr" />
Notes
- According to the latest HTML and CSS specifications, it is recommended to use
background-colorinstead ofborder-colorto change the color of the<hr>element, as the<hr>element is typically treated as a block-level element, and its border color may not produce the expected effect. - To ensure compatibility and consistent appearance, it is a good practice to remove or reset the
borderproperty before changing the color.
This covers the methods for changing the color of the <hr> element.