Matt
Matt

Reputation: 3848

How do I put a div over a specific line of a p?

I have a < p > tag full of text. When rendered to the page its displayed in 5 lines. I want to style and position a < div > tag to highlight a given line without needing to touch the < p > tag or its contents, preferably using jQuery.

So the markup looks like

<p>one fish two fish red fish zoo fish fifth fish</p>

And rendered looks like

one fish
two fish
red fish
zoo fish
fifth fish

And I want a transparent red div on top of "red fish" line 3.

I've tried nothing and I'm all out of ideas.

In response to Matt Burland's questions: I'm to create a function which, given an element P and a line number, places a colored box over that line as rendered.

The p could be rendered as any number of lines.

The window size is fixed so thats one thing I don't have to worry about.

Other functionality depends on the DOM of the page. I can insert a div a tag but not much else.

Upvotes: 0

Views: 211

Answers (3)

Yuriy Galanter
Yuriy Galanter

Reputation: 39807

If you don't want to depend on formatting (line positions may change etc.) and you don't want to change the original <P>, you can clone it - highlight required text and superimpose cloned one over original one:

HTML

<p id="text">one fish two fish red fish zoo fish fifth fish</p>

CSS

#text {
    width:50px;
}

.highlight {
    background-color:red    
}

JS

var $text = $('#text');
var match = "red fish";

var $newtext = $text.clone().html($text.html().replace(match, '<span class="highlight">' + match + '</span>'))

$newtext.appendTo('body').offset($text.offset())

Demo: http://jsfiddle.net/j4UfM/1/

You can remove highlighted copy as needed.

Upvotes: 0

gagge
gagge

Reputation: 142

It's an really bad idea to do it like this. As other have told a list element is the proper way to do it. But If you need to keep the P intact you can set the line-height and do the math to place an div our whatever you want as overlay.

CSS:

line-height: 22px;

JS:

var pHeight = $('p').height();
var lineHeight = parseInt($('p').css('line-height'));
var selectedLine = 3;
$('#overlay').css('top', -Math.abs(selectedLine * lineHeight));

See the fiddle: http://jsfiddle.net/JVxdJ/

Upvotes: 0

kei
kei

Reputation: 20521

DEMO

JS

$p = $('p').first();
$pHeight = $p.height()/5;
$pTop = $p.offset().top+(2*$pHeight);
$p.after('<div id="IvetriednothingandImalloutofideas" style="height:'+$pHeight+'px;top:'+$pTop+'px">');

CSS

p {
    outline:1px solid #ccc;
    width:60px; 
}

#IvetriednothingandImalloutofideas {
    background-color:rgba(255,0,0,0.2);
    width:60px;
    position:absolute;
}

Upvotes: 3

Related Questions