用CSS着色单个单词 [英] Coloring a single word with CSS

查看:150
本文介绍了用CSS着色单个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置< pre> 块中的单个单词的颜色(粗略地说,用于显示具有语法高亮的代码)。 < font> 标签已被弃用,有利于使用CSS,公平;所需的语法是什么?特别是,在什么元素应该包裹词?我以前使用< div> 来标记CSS样式的文本块,但这似乎只适用于标记整个段落。

解决方案

您应该使用最简单,最通用的内联元素: < span> 。对于每种类型的令牌,给一个或多个适当的类。例如:

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

查看更新: StackOverflow还会执行代码突出显示 - 上面的代码已突出显示!它的HTML是什么样子的?查看源HTML显示第一行使用

加亮显示。

 < 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>

//它在


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.

解决方案

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

这篇关于用CSS着色单个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆