CSS underline color
CSS Underline Color
In web design, underline is a common decorative effect that adds a horizontal line below text to emphasize it. Typically, the underline color is the same as the text color, but in some cases, you may want a different color. This article will detail how to set the underline color using CSS.
Using the text-decoration-color Property
CSS3 adds the text-decoration-color
property, which is used to set the color of text decoration lines, including underlines, strikethroughs, and overlines. In practice, you can specify the underline color by setting the text-decoration-color
property.
span {
text-decoration: underline;
text-decoration-color: red;
}
In the example above, we added a red underline to the span
element. This way, we can quickly and easily set the underline color.
Using the ::after Pseudo-Element
If you want to customize the underline of an element, you can use the ::after
pseudo-element. Here is a sample code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Underline Color</title>
<style>
.underline {
position: relative;
}
.underline::after {
content: '';
position: absolute;
left: 0;
bottom: -2px;
width: 100%;
height: 2px;
background-color: blue;
z-index: -1;
}
</style>
</head>
<body>
<p class="underline">This is a paragraph with custom underline color.</p>
</body>
</html>
In the above code, we achieve the underline effect by adding a pseudo-element ::after
to the p
element containing the text. You can change the underline color by adjusting the background-color
as needed.
Avoid Confusion with Text Underline
Note that if you set both the text underline and text-decoration-color
, confusion may occur. In this case, the text underline and the underline set by text-decoration-color
will overlap, resulting in an unsightly appearance.
To avoid this, you can choose one of the following methods to set the underline color, or use appropriate layout to avoid overlap. Alternatively, you can dynamically set the underline color using JavaScript or other methods for more flexible effects.
Summary
Through the above introduction, we learned how to set the underline color with CSS. You can use the text-decoration-color
property to set the underline color directly, or use the ::after
pseudo-element to achieve a more customized effect. In actual applications, choose the appropriate method according to specific needs to avoid confusion and overlap, thereby optimizing the display effect of the page.