Emphasizing lines with highlight.js
Asked Answered
B

2

12

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

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

Backpack answered 20/3, 2015 at 18:7 Comment(0)
A
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

Archiphoneme answered 23/7, 2016 at 21:0 Comment(1)
<mark></mark> without class="highlight-inline" worked better for me. This way the font color of highlight.js is preserved.Kirchner
G
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/[email protected]/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

Gibb answered 27/2, 2019 at 8:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.