CSS selector to highlight only labels with no child elements

I have a basic html form where tags label

are used to define field names and where tags label

are used around checkboxes so that the user clicking on the text next to the checkbox also selects the checkbox.

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

      

What is the best CSS to have my field name in bold ("Valid?") But my checkbox handle is not bold?

I've tried several options, adding different :not

and :empty

, but I don't end up in the right selector, either both are in bold or not in bold. I know my: empty doesn't work since the messes text element, but this should be an easy way to only bold fonts that only have text elements.

label:empty {
    font-weight: bold;
}

      

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

+3


source to share


3 answers


You can use the following selector, for example:

label {
   font-weight: bold;
}

label + label { 
    font-weight: normal
}

      



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

+5


source


The class pseudo-class :empty

is for elements that have no children (not even spaces).

The pseudo-class can be used like this: http://jsfiddle.net/3z1pnv71/ .

HTML:

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

      

CSS

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

      



EDIT: It is also possible to keep all text elements in HTML and use the following approach if appropriate: 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;
}

      

+2


source


Found several solutions for this, both of which work because the label handle is always the first label in the parent 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 the label only has a text element, but that at least works in most cases.

0


source







All Articles