I am trying to create a multicolor link. I have tried a couple of variations, none of which work.

<a href="URL">Black text <span style="color:red">red text</span> black test</a>
<a href="URL">Black text <span class="rd">red text</span> black test</a>

Does anyone know how to do this?

Dani AI

Generated

is right that wrapping each colored segment in a span is a correct approach. The odd behavior described — wrapped text showing the expected black while the same unwrapped text did not — points to the stylesheet, not HTML: most often a rule targets descendants (for example a span { ... } or a * { ... }) or link pseudo-classes are incomplete (only a:link set, while the link is :visited).

Quick troubleshooting steps:

  • Open your browser inspector and check the computed color on the anchor and on the inner elements. The inspector shows which selector is winning and why.
  • Search your CSS for selectors like a span, a *, a > span or for rules only applying to :link and not :visited. Those are the usual culprits.
  • Prefer explicit rules on the anchor itself and classed spans for colored segments. As a safe pattern, set the anchor color for both normal and visited states, and give spans explicit classes for alternate colors.

Example CSS patterns to consider (use classes instead of inline styles for maintainability):

a, a:visited { color: #000; }
a .red { color: #c00; }   /* colored segments */
a .normal { color: inherit; } /* force inheritance where needed */

Avoid using !important unless necessary; instead fix selector specificity or the mistaken descendant selector. Also remember to style :hover and :focus for accessibility and ensure sufficient contrast.

For background reading on why selectors and inheritance behave this way, see MDN on CSS specificity and inheritance:

Recommended Answers

All 2 Replies

Your first link is correct styling the red text. However, its a hyperlink so the other text is not of black color by default. For example, this would work...

<a href="URL">
  <span style="color:black;">Black text</span>
  <span style="color:red">red text</span>
  <span style="color:black;">black text</span>
</a>

Thanks.

I had already defined links to be black. The following code worked.

<a href="URL">
  <span >Black text</span>
  <span style="color:red">red text</span>
  <span >black text</span>
</a>

Suprisingly the following code did not

<a href="URL">
  Black text
  <span style="color:red">red text</span>
  black text
</a>

Perhaps it something weird elsewhere in my style sheet.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.