mary r
mary r

Reputation: 93

Change style of an element when focus is another element

I need to change the style of a div when focus is on another div.I tried the following code but didn't work

<div id="one">
<div id="two">

my css file looks like this

#one {
    background-color:red;
}
#two:focus #one {
    background-color:green;
}

Any help is really appreciated!

Upvotes: 8

Views: 11525

Answers (3)

Augustine Godwin
Augustine Godwin

Reputation: 1

    <div id="parent">
        <input type="text" id="one"/>
        <input type="text" id="two"/>
    </div>
    #parent:has(#one:focus) {
        color: red;
    }

just try making the element you want to style the parent that is what i did when i faced something like this

Upvotes: 0

Mr. Alien
Mr. Alien

Reputation: 157284

If you mean :hover and not :focus, then use adjacent selector, using + which will select your #two on :hover of #one

#one:hover + #two {
   color: red;
}

Demo

Note: You've a typo, like if instead of id, also, close your div elements.


As you commented that you want to use focus on div, than replace :hover with :focus but the adjacent selector logic stays the same...

<div id="one" tabindex="1">One, Hover Me</div>
<div id="two">Two</div>

#one:focus + #two {
   color: red;
}

Demo (Press the first line and see the effect) OR (Click on the result window in jsfiddle, and press the tab button once)

Upvotes: 14

ahalya
ahalya

Reputation: 192

Using jquery to fix the issue or using hover property in css

Upvotes: -2

Related Questions