views:

864

answers:

3

Hi there,

I've been battling to get this right...basically I have the following HTML setup:

<div class="box10">
   <span class="label01">Name:</span>
   <input class="tboxes" type="textbox" />
</div>

"span.label01" is an inline element, and appears to the left of the textbox "input.tboxes". What I am trying to do attach some style to "span.label01" AND "div.box10" when the textbox receives focus.

I have tried the following CSS code:

input.tboxes:focus span.label01 {
   color:#FF9900;
   ...
}

but nothing happens. I know this is a CSS selector issue, but I just can't seem to get it right. I have even tried adjacent sibling selectors, and nothing. Can anyone help me here? TIA!

+3  A: 

Your selector at the moment is looking for a span inside an input. As far as I'm aware, what you're trying to do isn't really reliably possible with the current state of CSS selector support.

I'd be tempted to do it with a bit of jQuery like so:

$("input.tboxes").focus(function() {
    $(this)
    .parent("div:first")
        .addClass("focussed")
        .find("span")
            .addClass("focussed");
});

That should do what you're wanting to do if you then set styling for .label01.focussed and .box10.focussed.

jsidnell
BTW, the selectors mentioned in that last paragraph aren't a mistake - by joining classes like that (with no space between) they're basically saying "the element that has class label01 and focussed" or "the element that has class box10 and focussed".
jsidnell
Hi! and thanx for the quick reply! you're right, I know that javascript would certainly do the trick, although I was hoping on a CSS-only trick. thanx for help though
Shalan
+4  A: 

No – you can't do this with a CSS selector. Quote from Wikipedia:

Selectors are unable to ascend

CSS offers no way to select a parent or ancestor of element that satisfies certain criteria. A more advanced selector scheme (such as XPath) would enable more sophisticated stylesheets. However, the major reasons for the CSS Working Group rejecting proposals for > parent selectors are related to browser performance and incremental rendering issues.

You could, however, do this with some simple JavaScript:

// with jQuery:
$('input.tboxes').focus(function() {
    $(this).parent().find('span.label01').addClass('active');
});
moff
hi Moff, thanx for the assist! As mentioned in my prior comment to jsidnell, I guess a javascript approach is my only option. Thanx anyway!
Shalan
A: 

This is entirely possible through the use of sibling selectors.

input.tboxes:focus + span.label01 {
   color:#FF9900;
   ...
}

This rule will apply to label01 whenever the input is focused.

However, this only works when the span is to the right of the input, so you'll have to switch the places of the elements. A quick "position:relative" on the div and "float: left" on the span will move them back in place though.

peroo