What I want to accomplish is to have one division with the first part of the text red and the second part green. How would I do that?

Dani AI

Generated

A single parent DIV is fine. The cleanest, maintainable approach is to mark the two pieces of text as small inline elements and style those with classes (reusable, low-specificity rules). 's example with separate blocks will work, but it creates extra markup and can change layout; was right to point toward inline-level formatting. The pattern below focuses on clarity, reusability, and accessibility.

<div class="line">
  This is the first part <span class="text--red">red part</span> and this is the <span class="text--green">green part</span>.
</div>

<style>
:root {
  --red: #b12;   /* choose colors that meet contrast requirements */
  --green: #0a6;
}
.text--red { color: var(--red); }
.text--green { color: var(--green); }
</style>

Troubleshooting and best practices:

  • Prefer classes over IDs for styling so rules are reusable and easier to override.
  • Keep the inline elements truly inline (default for span). If you wrap blocks, layout can change.
  • Pick accessible colors and test contrast (WCAG). See the WCAG guidance: WCAG standards.
  • For dynamic content, toggle classes from JavaScript rather than injecting inline styles; avoid heavy libraries when simple DOM class toggling suffices.
  • If the colored parts carry meaning (emphasis, status), use semantic tags (for example, <strong>) or ARIA where appropriate so assistive tech gets the semantics. More on the inline element: span element on MDN.

This keeps one DIV around the whole phrase while letting each part be styled independently, accessible, and easy to maintain.

Recommended Answers

All 2 Replies

You mean that you wnt to have the first part of a text green and the second red

//add your css
<style>

#green p{color:green;}
#red   p{color :red;}

</style>
<div id="main">

    <div id="green">
    <p>Hello</p>
    </div>

    <div id="red">
    <p>World</p>
    </div>

</div>
commented: I imagined something very complicated. Thank you! +0

If one div is required, you can place a span element around the text that you want to format differently, then apply a style on that span element. Or you can do this with jQuery. Please clarify exactly what you are trying to do.

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.