user1199595
user1199595

Reputation: 426

Css change color on parent

Is there a way to change color off a parent when an input gets focus Check out the demo. I want the div to be red instead of blue when input has focus.

Demo

Upvotes: 1

Views: 22733

Answers (6)

user1721049
user1721049

Reputation:

javascript also works here look at the code below,it is more flexible than just using css

<!DOCTYPE html>
<html>
<head>
  <script>
    function myFunction(){
      document.getElementById('box').style.background="red";

    }
  </script>  
<title>JS Bin</title>
</head>
<body>
  <div id="box" style="background-color:blue">
    <input onfocus="myFunction()" />
  </div>
</body>
</html>

Upvotes: 0

iambriansreed
iambriansreed

Reputation: 22241

CSS Only Approach

Fiddle

http://jsfiddle.net/GT5sT/

CSS

input {
    position: relative;
    z-index: 2;
}
input:focus,
input:focus + div { background-color: red }
div {
    position: relative;
    background-color: blue;
}
div.background-hack {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1;
}

HTML

<div>
    <input />
    <div class="background-hack"></div>
</div>

Upvotes: 1

gvee
gvee

Reputation: 17161

Here's a bit of a cheaty way of doing it using CSS only...

DEMO: http://jsfiddle.net/gvee/6fRUd/

HTML

<div>
    <input type="text" />
</div>

CSS

div {
    overflow: hidden;
    background-color: blue;
}
div * {
    position: relative;
    z-index: 10;
}
div input[type=text]:focus {
    background-color: red;
    box-shadow: 0 0 10000px 10000px lime;
    z-index: 5;
}

Upvotes: 5

James Nicholson
James Nicholson

Reputation: 973

A jQuery approach would be using .parent()

<script>$("p").parent(".selected").css("background", "yellow");</script>

http://api.jquery.com/parent/

Upvotes: 1

user2365865
user2365865

Reputation:

I think you can't do that in pure CSS, but you can use Javascript:

http://jsbin.com/uvon/1/edit?html,js,output

var input = document.getElementById('input');
var div = document.getElementById('div');

input.onfocus = function(){
  input.style.backgroundColor = "red";
  div.style.backgroundColor = "red";
}

input.onblur = function(){
  input.style.backgroundColor = "white";
  div.style.backgroundColor = "blue";
}

Upvotes: 1

user1157393
user1157393

Reputation:

You will have to use javascript.

Here is a short script using jquery.

$('#input').focus(function(){
  $('#box').css('background-color','red');
});

This is assuming your input has an id of input and blue box has an id of box.

Upvotes: 0

Related Questions