1

I have this structure:

<span class='user_name'>
  Peter Green <span class='remove_user'>X</span>
</span>

I am trying to change the background color of the .username and .remove_user when is hovered .remove_user.

Is there any way to do it with CSS without involving javascript?

Thank you

user984621
  • 41,002
  • 66
  • 200
  • 371

2 Answers2

3

As commented by @HashemQolami, There is no parent selector in CSS (yet) but you can try this:

JSFiddle - DEMO

#checkbox {
    left: -9999px;
    position: absolute;
}
#checkbox:hover + .user_name {
    background-color: #0f0;
}
.user_name {
    width: 400px;
    height: 200px;
    display: block;
    background: #f00;
}
#label {
    display: inline-block;
    background: #0f0;
    padding: 5px;
}
#label:hover {
    background: #f00;
}
<input type="checkbox" id="checkbox">
<span class='user_name'>
    Peter Green <span class='remove_user'><label for="checkbox" id="label">X</label></span>
</span>

OR: You could simply achieve this by using jQuery like this:

JSFiddle - DEMO

$('.remove_user').hover(function () {
    $(this).toggleClass('hover-1').parent('span.user_name').toggleClass('hover-2');
});
.user_name {
    width: 400px;
    height: 200px;
    display: block;
    background: #f00;
}
.remove_user {
    background: #0f0;
    padding: 5px;
    display: inline-block;
}
.hover-1 {
    background: #f00;
}
.hover-2 {
    background: #0f0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class='user_name'>
  Peter Green <span class='remove_user'>X</span>
</span>
Community
  • 1
  • 1
Anonymous
  • 9,152
  • 2
  • 19
  • 36
0

CSS4 has a "!" selector to apply a style to a parent, using a target allows selecting an ant or uncle.

.user_name! .remove_user:hover{
   color: red; /* applied to parent .user_name element on .remove_user hover */
}

There is a lib that allows this selector to be used if jQuery is being used. https://github.com/Idered/cssParentSelector

However jquery already has a parent selector $(".remove_user:parent") so cssParentSelector does not help with minimizing javascript usage. It only allows for an easier transition when CSS4 is supported.

So the choice today is which flavor of javascript to use to accomplish it.

Wayne
  • 4,424
  • 1
  • 21
  • 24