mardi 5 mai 2015

Hover over a pre - how to highlight a single line with plain CSS?

I have some <pre> blocks.

Would it be possible, using just CSS, to highlight single lines when hovering over them?

== Update ==

Here is some sample code:

<pre>
#include <stdio.h>

int main()
    {
       printf("Hello World");
       return 0;
    }
</pre>

When lines become longer it would be useful to have them highlighted when hovering.

The source file can't be read via PHP, or I'd split it into separate <pre> lines, with a trivial pre:hover CSS.

pre:nth-child is not a solution, because code lines are not "children" in the CSS sense.

pre:first-line works, but of course just for the first line.

== Update 2 ==

Since CSS seems to be limited to first-line, and thanks to Zeke suggestion, I found an almost simple way to have what I want.

HTML:

<pre id="raw">
#include <stdio.h>

int main()
    {
       printf("Hello World");
       return 0;
    }
</pre>
<!-- 1×1 transparent PNG for the onload -->
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP4/x8AAwAB/2+Bq7YAAAAASUVORK5CYII=" onload="PreHover()" />

CSS:

#pre div:hover {
    background: #ff0;
}

Vanilla Javascript:

function PreHover() {
    var output = '';
    var preBox = document.getElementById('raw');
    var txt = preBox.innerHTML.split('\n');
    for(var x=0;x<txt.length-1;x++) {
        output = output + '<div>'+txt[x]+'</div>';
    }
    preBox.innerHTML = output;
}

JSFiddle here

Aucun commentaire:

Enregistrer un commentaire