Search code examples
htmlcssstylesheet

I want to apply an existing CSS style to all labels on a page. How?


Note, this is different than the older question How can I apply CSS on all buttons which are present in that page? because this is an already existing style. So given that a style, which we'll call "standard_label_style" already exists in an included CSS file, what can I do to say that all the labels on this page should have that style short of adding:

class="standard_label_style"

to each and every one? And yes, I know I could apply the styles ex-post-facto with a snippet of jQuery or JavaScript code. I'm just trying to learn how I'm supposed to do it with CSS.

Follow Up

I've gotten several comments that say just use syntax like this .standard_label_style, label... Unfortunately that does nothing like what I want. That would allow me to apply additional rules to the standard_label_style class, as well as rules to labels within this page, but would not allow me to apply that style to all the labels on this page. To see an example of this, here is a stylesheet and html to demonstrate. The label without a class will still not appear in red but that's what I'm hoping to have happen. I want to apply an existing class to all those labels on the page, not just the one with the class and without adding new styling on this page, the existing style should be the only style.

included.css:

.standard_label_style { color: red; }

test.html:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="included.css">
    <style>
      .standard_label_style, label { }
    </style>
  </head>
  <body>
    <label class="standard_label_style">Test Label</label><br/>
    <label>Unclassed Test Label</label>
  </body>
</html>

Solution

  • CSS doesn't really work like that.

    You can apply a style to all labels directly:

    label {
        color: Lime;
    }
    

    or apply a class to all labels

    .labelClass {
        color: Lime;
    }
    
    <label class="labelClass"></label>
    

    You can also have multiple selectors, so you could ammend your current style to be

    .labelClass, label {
        color: Lime;
    }
    

    What you can't do in standard CSS is something like

    label {
        .labelClass;
    }
    

    The good news is that there are a bunch of server side libraries which make CSS suck less and let you do exactly this kind of thing, see for example dotLess if you're using .NET which provides nested rules and a basic inheratance model.