views:

404

answers:

1

Is there a way in CSS to select the label fields which are bound to input fields (via the for attribute) having the required attribute set?

Something like -- label:input[required]

Currently, I'm adding class=required to labels and inputs for styling. I now have the HTML5 attribute required="required" in the required input fields. Would be nice to remove the redundant class attributes.

Closest answer I found was at: http://stackoverflow.com/questions/1431726/css-selector-for-a-checked-radio-buttons-label

However that doesn't use the for attribute, but would require that the label is directly adjacent to the input in the html.

+2  A: 

How about CSS 2 Attribute Selectors It is pretty compatible amongst browsers.

Example:

<style>
label[required=required]
{
color: blue;
}
</style>
<label required="required" for="one">Label:</label><input name="one" id="one" />

Also check this out.

Tom
Apparently questions and answers use formatting, but comments do not.The problem with that suggestion is that the required attribute belongs to the input element, not the label element.<label for="email">E-mail address:</label><input id="email" type="email" name="email" required="required"/>Also in the CSS, better off just saying:input[required] because the only valid markup is:HTML -> requiredXHTML -> required="required"required="false" or anything like that is not valid.
Ted Bergeron
Also see: http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#the-required-attribute
Ted Bergeron
yeah, required=required is unnecessary. But if then he wants to be able to get all of the label tags attached to inputs that have the required attribute I don't think that is possible. You can get all the inputs @required `input[required]`, but not all the labels unless they are a child node of the input, which is incorrect even in HTML.
Tom