focusing on an element changes another's CSS

2020-03-01 09:41发布

I want to change an element's color Hdr_nav_search_box when focusing on another element Hdr_nav_search_input. Here are the codes : http://jsfiddle.net/FJAYk/4/ I don not see why this is not working.

<input class="Hdr_nav_search_input" />
<div class="Hdr_nav_search_box" /><span>search for location....</span><i>for example: blah blah</i></div>

-

.Hdr_nav_search_box{
padding: 0 5px;
margin: 7.5px 0;
width:300px;
height: 25px;
background: white;
 }
.Hdr_nav_search_input:focus .Hdr_nav_search_box{
color: #d4d4d4;
 }
.Hdr_nav_search_box span,.Hdr_nav_search_box i{
line-height: 25px;
color: gray;
}
.Hdr_nav_search_input{
padding: 0 5px;
margin: 7.5px 0;
border: 0;
z-index: 2;
position: absolute;
width:300px;
height: 25px;
background: transparent;    
}

标签: html css focus
1条回答
家丑人穷心不美
2楼-- · 2020-03-01 10:23

There were a few problems with your styles. Firstly your selector to target the box isn't quite right.

.Hdr_nav_search_input:focus .Hdr_nav_search_box

That is applying selecting all .Hdr_nav_search_box where they are a descendant of .Hdr_nav_search_input. It's actually a sibling so you want to use the next sibling selector +:

.Hdr_nav_search_input:focus + .Hdr_nav_search_box

Secondly this selector would be overriding your colour change if it was working.

.Hdr_nav_search_box span,.Hdr_nav_search_box i{
    ...
}

You could use simply

.Hdr_nav_search_box {
    ...
}

Here is a demo and the style changes I made to get it working.

jsFiddle

.Hdr_nav_search_input:focus + .Hdr_nav_search_box {
    color: #F00;
 }
.Hdr_nav_search_box {
    line-height: 25px;
    color: gray;
}
查看更多
登录 后发表回答