Alex Rivera | Logout

CSS Selector for selecting an element that comes BEFORE another element?

Asked 2009-01-29T18:19:27.197
73

I'm working on a login page for my website and I want to bold the label that comes before the input box when the text box gains focus. Right now I have the following markup:

<label for="username">Username:</label>
<input type="textbox" id="username" />

<label for="password">Password:</label>
<input type="textbox" id="password" />

I can use the adjacent selector to select the label after the text box, but I can't select the element before it. I can use this CSS selector rule, but it only selects the label after, so when the username text box gains focus, the password label becomes bold.

input:focus + label {font-weight: bold}

Is there anything I can do to make this work? I know JavaScript could be used to easily do this, but I'd like to use a purely CSS-based solution if possible, I just can't figure out a way to do it.

Edit
Report

1 Answer

5

Floating the input element to the right, achieves correct element order without changing order of "Username" and ":" in the label text that you get with direction:rtl.

<style type="text/css">
    form {text-align: right;}
    input:focus + label {font-weight: bold}
    input {float:right; clear:right;}
</style>
<form>
    <div>
        <input type="text" id="username" />
        <label for="username">Username:</label>
    </div>
    <div>
        <input type="password" id="password" />
        <label for="password">Password:</label>
    </div>
</form>
answered 2009-01-29T19:58:43.313

Your Answer