Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

how to select before elements

<label>User Name</label>

IN MY STYLESHEET there is an input element with an type attribute of text

<input type="text">

i want that when someone clicked on the input element the colour of label changes there are many ways to do it using javascript and jquery but i want this to be done with css

there are many ways to select a after element using child selectors but they are only useful for selecting an after element

is there any way to do so with css ?

2 Answers

Steven Parker
Steven Parker
231,261 Points

The label must come after the input in the HTML to do this. But the CSS can also make the label appear first:

page.html
<input type="text">
<label>User Name</label>
styles.css
label {
  float: left;
  margin-right: 1ex;
}
input:focus + label {
  color: red;
}

hey Steven input and label are inline elements so they appear side by side but my problem is this please look at it:

<div> <label>User Name</label> </div> <input type="text">

Steven Parker
Steven Parker
231,261 Points

If you want to use my suggestion, they need to be arranged like this instead:

<div><input type="text"><label>User Name</label></div> 

hey steven i want the label to come before input element and the label should take the entire width of the webpage so that the input element should come after the label

Steven Parker
Steven Parker
231,261 Points

My suggestion uses the CSS to make the label display in front even though it comes after in the HTML. I'm not sure what you mean by "entire width", it would help to see the complete code (both HTML and CSS).