Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coloring a single word with CSS

Tags:

html

css

I want to set the color of individual words within a <pre> block (roughly speaking, for displaying code with syntax highlighting). The <font> tag is deprecated in favor of using CSS, fair enough; what's the required syntax? In particular, in what element should the words be wrapped? I've previously used <div> to mark chunks of text for CSS styling, but that would seem only suitable for marking full paragraphs.

like image 201
rwallace Avatar asked May 05 '12 16:05

rwallace


People also ask

How do I color a specific word in CSS?

To colored just one word you can use <span style="your style"> WORD</span> . This way you don't have to style the whole paragraph.

How do I make one word a color in HTML?

To set the font color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property color. HTML5 do not support the <font> tag, so the CSS style is used to add font color.

How do I color the first word in CSS?

Solutions with CSS and HTML If you want to change the color of the first word of a text, you can use the CSS :before pseudo-element, which is used to add any element. Its value is defined with the content property. If it is not used, the content will not be generated and inserted.

How do I change the color of one letter in CSS?

From css you can only change an elements property so you need to insert the letter "A" in another element like this: ST<span>A</span>CK OVER FLOW just the 'A' letter is red! ST<span class="myRedA">A</span>CK OVER FLOW just the '<A' letter is red!


1 Answers

You should use the simplest, most generic inline element: <span>. For each type of token, give one or more appropriate classes to the span. For example:

<span class="type">int</span>
<span class="name">foo</span>
<span class="op">=</span>
<span class="number literal">42</span>

See it in action.

Update: StackOverflow also does code highlighting -- the code just above is highlighted! What does the HTML for that look like? Viewing the source HTML shows that the first line is highlighted using

<span class="tag">&lt;span</span>
<span class="pln"> </span>
<span class="atn">class</span>
<span class="pun">=</span>
<span class="atv">"type"</span>
<span class="tag">&gt;</span>
<span class="pln">int</span>
<span class="tag">&lt;/span&gt;</span>

// and it goes on
like image 96
Jon Avatar answered Oct 17 '22 08:10

Jon