Pranay Sute
Pranay Sute

Reputation: 431

Change the CSS of span div on focus of the input div using CSS

I want to change the background image of a span div on the focus of the input type. I have tried to change with appropriate parent classes but it is not working for me. Any help would be appreciated. Here is my code.

.enq-form-section input[name='treat-cat']:hover .enq-form-section .enq-form .tc-img {
  background: #ccc !important;
}
<div class="form-group">
  <span class="tc-img"></span>
  <input type="text" class="form-control" placeholder="Treatment Category" name="treat-cat">
</div>

Upvotes: 2

Views: 4201

Answers (2)

Praveen Puglia
Praveen Puglia

Reputation: 5631

Can you change the order in which the span and the input elements are written? If so, it would be so easy. Here's an example.

.form-control:hover + .tc-img,
.form-control:focus + .tc-img {
  background: red;
}
<div class="form-group">
  <input type="text" class="form-control" placeholder="Treatment Category" name="treat-cat">
  <span class="tc-img">SOME CONTENT IN HERE</span>
</div>

Info

CSS makes it impossible to select previous elements or parent elements. It does it for a reason.

If you can't change the markup then you will have to use JavaScript to target the previous element.

Assuming you had jQuery, you would do something as follows.

jQuery(".form-control")
.on("focus", function(){
    // set background color on focus
    $(this).prev().css("backgroundColor","tomato");
})
.on("blur", function(){
    // remove background color on blur
    $(this).prev().css("backgroundColor","none");
});

Upvotes: 6

DawnPatrol
DawnPatrol

Reputation: 156

It is difficult to understand the css with such a small amount of html provided. What I can tell you though is that what you are attempting to do cannot be done with css. When you use hover states, they will only work on either the item that is being hovered on, or it's children. You cannot put a hover state on an element and then try to edit it's parents or siblings.

What you are trying to do needs to be done through javascript. Try using a mouseOver event with the value of a function that changes the background image of the span.

onmouseover reference: http://www.w3schools.com/jsref/event_onmouseover.asp

Upvotes: 0

Related Questions