Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Focus unable to affect other elements [duplicate]

I've looked around and I can't find the solution for making a title appear when a form is focused. I'm probably missing something glaringly obvious (probably that it can't be done with this selector).

Ideally I'd like to avoid jQuery and stick to CSS (more advanced CSS is fine) as I have no plans to support IE - I like to learn, but IE is too much of a pain to me.

This is my CSS at the moment:

#search-title {
    color: rgba(0, 0, 0, 0);
    font-size: 20px;
    font-weight: 300;
    margin-left: -30px;
    -webkit-transition: all 200ms;
    -moz-transition: all 200ms;
    -ms-transition: all 200ms;
    -o-transition: all 200ms;
    transition: all 200ms;
}

input[type="text"]:focus #search-title {
    color: #F70;
    margin-left: 35px;
}

Thanks in advance,

Sam

like image 574
2xAA Avatar asked Sep 29 '26 03:09

2xAA


2 Answers

Ok, I have a solution that works purely with CSS but you are going to have to jiggle your html elements around a little bit.

The only way to select another element that is not a descendant of a reference element (that I know of) is to use a sibling selector (general or adjacent). However, that solution relies on the reference element (the input) and the target (the title) being siblings in the dom hierarchy.

Here's a quick example : http://jsfiddle.net/7AaDc/1/

For the record, the example uses the general sibling selector (~) but the adjacent (+) would work just as well in this case.

Here is a much better explanation of sibling (and child) selectors : http://css-tricks.com/child-and-sibling-selectors/

Here is a rundown of the compatibility issues associated with sibling selectors : http://caniuse.com/#search=sibling (tl;dr, pretty widely supported these days)

like image 198
Ninjabiscuit Avatar answered Sep 30 '26 16:09

Ninjabiscuit


You've used the descendant selector, which means “#search-title” must appear within your input element for it to match the rule — and that's clearly not going to happen.

There isn't actually a CSS selector which will match #search-title when your input is any particular state given how your document is structured.

like image 39
Mo. Avatar answered Sep 30 '26 17:09

Mo.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!