Hippp Hipp
Hippp Hipp

Reputation: 45

How to avoid overlapping HTML tags to highlight text

In the code below, I have three hover texts and the world "hello". The first two highlight parts of "hello", and I want the 3rd to highlight all of "hello". Wrapping all the first two spans in a 3rd span doesn't work, and I understand why. I know that I cannot overlap HTML tags, and I don't know if nesting is the solution.

How would you set this up so that the third hover works?

http://jsfiddle.net/CAWhP/3/

Here's the HTML:

<div id="test1"> highlight hel in hello</div>

<div id="test2"> highlight lo in hello</div>

<div id="test3"> highlight all of hello</div>

<span class="testspan1"> hel</span><span class="testspan2">lo </span>

Here's the CSS:

#test1:hover ~ .testspan1{

   background: red;
}

#test2:hover ~ .testspan2{

   background: red;
}
#test3:hover ~ .testspan3{

   background: red;
}

Upvotes: 1

Views: 1891

Answers (3)

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

Not sure why you want to do this, but to solve the problem, I guess you could do this:

#test3:hover ~ .testspan1,
#test3:hover ~ .testspan2 {
   background: red;
}

Complete and shorter version:

Since all rules apply the same property, you could shorten your complete CSS to this:

#test1:hover ~ .testspan1,
#test2:hover ~ .testspan2,
#test3:hover ~ .testspan1,
#test3:hover ~ .testspan2
{
   background: red;
}

Working example

Upvotes: 1

Mr. Alien
Mr. Alien

Reputation: 157294

Select the relevant element

#test3:hover ~ span{
   background: red;
}

Demo

Or else you can also use this

#test3:hover ~ span.testspan1, #test3:hover ~ span.testspan2 {
   background: red;
}

Demo 2

Upvotes: 1

tckmn
tckmn

Reputation: 59273

Here is a workaround: JSFiddle

#test3:hover ~ .testspan1 {

background: red;

}

#test3:hover ~ .testspan2 {

background: red;

}

You could also separate the classes with commas, like #test3:hover ~ .testspan1, #test3:hover ~ .testspan2. That would work if you want both spans to have the same style.

Upvotes: 0

Related Questions