Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Apply CSS to child DIV only

OK, let's say I have a similar structure like the one following :

<div comp-id='one'>
    <div comp-id='two'>
         <div comp-id='three'>
         ...
         </div>
    </div>
</div>

All I want to do is to apply a hover effect to the child (in this case, the one with comp-id="three").


IMPORTANT NOTE : I don't want to target specifically [comp-id="three"]. I want to target any child, with no-matter-which comp-id value. In the real-world example, there may be infinite nested [comp-id]ed divs. I just need the innermost child.

What I'm trying to achieve :


My current CSS code :

[comp-id]:hover {
    box-shadow: inset 0 0 0 2px red;
    -webkit-box-shadow: inset 0 0 0 2px red;
    -moz-box-shadow: inset 0 0 0 2px red;
    -o-box-shadow: inset 0 0 0 2px red;
}

However, my current CSS highlights everything which is not what I want. I could think of a javascript-based solution. What about CSS?


Warning : I'm not such a guru with CSS, so this may be really simple... :-)

Upvotes: 2

Views: 275

Answers (4)

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

And... well... thanks to @BMH, this is what worked :

$('[comp-id]:not(.hover)').mousemove(function(e){
    $('[comp-id]').removeClass('hover');
    e.stopPropagation();
    $(this).addClass('hover');

});

Upvotes: 2

BMH
BMH

Reputation: 4340

This is a jQuery solution:

$('[comp-id]').mousemove(function(e){
    $(this).removeClass('hover');
    $(e.target).addClass('hover'); 
}).mouseleave(function(e){
    $(this).removeClass('hover');
});

http://jsfiddle.net/sMRMz/4/

Upvotes: 1

art-fan-vikram
art-fan-vikram

Reputation: 315

You can use '>' child selector for this,to stop the cascading styles

[comp-id]:hover {
    box-shadow: inset 0 0 0 2px red;
    -webkit-box-shadow: inset 0 0 0 2px red;
   -moz-box-shadow: inset 0 0 0 2px red;
    -o-box-shadow: inset 0 0 0 2px red;
}

[comp-id]:hover > *{
  box-shadow: none;
    -webkit-box-shadow: none;
   -moz-box-shadow: none;
    -o-box-shadow: none;
}

Upvotes: 0

DaKirsche
DaKirsche

Reputation: 352

Try something like this in jQuery:

CSS:

.hoverableClass:hover {
    box-shadow: inset 0 0 0 2px red;
    -webkit-box-shadow: inset 0 0 0 2px red;
    -moz-box-shadow: inset 0 0 0 2px red;
    -o-box-shadow: inset 0 0 0 2px red;
}

JS:

function deepSearch(parent){
    var b_ClassAdd = true;
    if (!parent){
        parent = $('body');
        b_ClassAdd = false;
    }

    var allDivChilds = parent.find('div[comp-id]');
    if ((!allDivChilds || allDivChilds.length == 0) && b_ClassAdd)
        parent.addClass('hoverableClass'); 
    else
        for (var i = 0; i < allDivChilds.length; i++)
            deepSearch($(allDivChilds[i]));
}

deepSearch();

This code is untested and just an idea for a solution.

Upvotes: 0

Related Questions