Jason W
Jason W

Reputation: 13179

CSS selector to bold only labels without child elements

I have a basic html form where label tags are used to define field names and where label tags are used around checkboxes so that a user clicking on the text next to a checkbox also selects the checkbox.

<label>Valid?</label>
<label>
    <input type="checkbox" />
    Yes
</label>

What CSS is the best practice so that my field name is bold ("Valid?"), but my checkbox descriptor is not bold?

I have tried several variations adding different :not and :empty, but I'm not hitting the right selector - either both are bold or neither are bold. I know my :empty isn't working since the text element messes that up, but there must be a simple way to only bold labels that have only text elements.

label:empty {
    font-weight: bold;
}

JS Fiddle: http://jsfiddle.net/z77tq8bs/

Upvotes: 4

Views: 4341

Answers (3)

DRD
DRD

Reputation: 5813

The :empty pseudo-class targets elements that have no children (not even a space).

The pseudo-class can be used in the following way: http://jsfiddle.net/3z1pnv71/.

HTML:

<label></label>
<label>
    <input type="checkbox" />
    Yes
</label>

CSS:

label:empty:before {
    content: "Valid?";
    font-weight: bold;
}

EDIT: It's also possible to keep all the textual elements in HTML and use the following approach, if it is suitable: http://jsfiddle.net/cqugufex/.

HTML:

<label data-text = "Valid?"></label>
<label>
    <input type="checkbox" />
    Yes
</label>

CSS:

label:empty:before {
    content: attr(data-text);
    font-weight: bold;
}

Upvotes: 2

Jason W
Jason W

Reputation: 13179

Found a few solutions to this, both of which work because the label descriptor is always the first label within the parent element, and any checkboxes are subsequent labels

Solution 1: first-of-type

label:first-of-type {
    font-weight: bold;
}

Solution 2: first-child

label:first-child {
    font-weight: bold;
}

I still haven't found a solution that finds if a label has only a text element, but this at least works for most cases.

Upvotes: 0

Inacio Schweller
Inacio Schweller

Reputation: 1986

You can use the next sibling selector, like this:

label {
   font-weight: bold;
}

label + label { 
    font-weight: normal
}

Check the fiddle: https://jsfiddle.net/8cLuhznb/

Upvotes: 6

Related Questions