12

Is there a way to emphasize lines with highlight.js?

For instance by coloring them differently, changing the background color, or other means.

user3761898
  • 1,143
  • 1
  • 8
  • 7

2 Answers2

7

You can use the HTML5's mark tag.
Let's take this block of Java code as an example:

<pre><code>
View.OnClickListener listener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(&#x22;TAG&#x22;, &#x22;Clicked!&#x22;);
    }
};
</code></pre>

which will be displayed as following:

highlightjs-1

and add a gray-on-yellow highlight for a part of the code:

<pre><code>
View.OnClickListener listener = <mark class="highlight-inline">new View.OnClickListener() {
    @Override
    public void onClick</mark>(View v) {
        Log.d(&#x22;TAG&#x22;, &#x22;Clicked!&#x22;);
    <mark class="highlight-inline">}</mark>
};
</code></pre>

<style type="text/css">
.highlight-inline {
    background:yellow;
    color:gray;
}
.highlight-inline span {
    background:inherit;
    color:inherit;
}
</style>

which will result as:

enter image description here

Alex Lipov
  • 13,503
  • 5
  • 64
  • 87
  • `` without `class="highlight-inline"` worked better for me. This way the font color of highlight.js is preserved. – Peter Jun 02 '18 at 00:53
5

You can also use highlightjs-highlight-lines.js.

This plugin enables you to emphasize some lines with background-color css.

The usage is below code, so you have only to add one line and one code into your HTML page.

<head>
...
<link rel="stylesheet" href="path/to/default.min.css">
<script src="path/to/highlight.min.js"></script>

<!-- Add this line ↓ -->
<script src="//cdn.jsdelivr.net/gh/TRSasasusu/highlightjs-highlight-lines.js@1.1.5/highlightjs-highlight-lines.min.js"></script>
<!-- Add this line ↑ -->

<script>
hljs.initHighlightingOnLoad();

// Add this code ↓
hljs.initHighlightLinesOnLoad([
    [{start: 1, end: 3, color: '#555'}, {start: 6, end: 6, color: 'yellow'},], // Highlight line 4 from line 2 and line 7 in the first <pre><code></code></pre> block.
    [{start: 2, end: 3, color: 'rgba(255, 255, 255, 0.2)'},], // Highlight line 4 from line 3 in the second <pre><code></code></pre> block.
]);
// Add this code ↑

</script>
...
</head>

Then, the result of the first <pre><code></code></pre> will look like this:

highlight demo

KyleMit
  • 30,350
  • 66
  • 462
  • 664
kishi
  • 59
  • 1
  • 5