Explain Codes LogoExplain Codes Logo

Changing the color of an hr element

html
css
styling
web-design
Alex KataevbyAlex Kataev·Aug 20, 2024
TLDR

The easiest way to change the color of an <hr> element is by manipulating its border-color using CSS. You could use hex (#ff0000), RGB (rgb(255,0,0)), or a color name (red). Here's a quick snippet:

hr { border: none; border-top: 2px solid red; /* Turns the line into a red carpet */ }

This code will replace the default style with a 2px thick linear red separator.

Consistent color across browsers

Getting the color of an <hr> to display consistently across different browsers can feel like taming a wild animal. So let's tame the beast.

Deal with browser specifics

Different browsers interpret <hr> styling in their unique way. To maintain consistency:

hr { border: none; height: 1px; background: tomato; /* Who doesn't like a nice tomato-colored line? */ }

In Chrome/Safari, border-color is your buddy for color assignment. Firefox/Opera get along with background-color more, and in IE7+, you'd have to use color:

hr { color: blue; /* IE is just being IE */ border: none; background-color: blue; /* Firefox/Opera jumped onto the blue line train */ }

Manage size and position

With color sorted, it's time to conquer size and position - it's more than just a thin line!

Adjust thickness and spacing

A few tweaks with border-top and margin can adjust thickness and spacing:

hr { border-top: 4px solid gold; /* Jackpot! The line struck gold! */ margin: 10px 0; /* Spacing above and below, deep breath line! */ }

Match and adapt

Although we've covered the most part, let's understand how <hr> bridges style information from its parent element.

Inheritance of style

The border-color: inherit; clause will let your <hr> drape the color scheme of its parent. Think of it as a chameleon, blending seamlessly:

hr { border: 0; border-top: 1px solid inherit; /* Chameleon activated! Now matches with parent */ }

Check out the SitePoint article to get nerdy about border-color inheritance.

Tailoring hr to your needs

Now that you've got the basics down, let's dive deeper. Style <hr> to elevate your site's unique aesthetics.

Clear out default

For a clean slate, erase all default border styles:

hr { border: none; /* Iz gone! */ }

Be subtle

If your design calls for a subtle divider, try softer hues:

hr { border-top: 1px solid antiquewhite; /* Light as a ghost whisper */ }

Bring in transparency

Adding transparency can make the <hr> look glassy:

hr { border-top: 2px solid rgba(0, 0, 0, 0.2); /* Semi-transparent ghost line */ }

Go with the trend

Stay relevant. Opt for a gradient for the trendiest <hr> in town:

hr { border: 0; height: 1px; background-image: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet); /* Because life's too short for monochrome lines */ }

Add animation transitions to make your website "alive".