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

不羁的心 提交于 2019-12-05 03:24:55

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.

To apply a style to every label on the page, use this CSS:

label {
/* styles... */
}

If you have an existing style (e.g. "standard_label_style") in the CSS already, you can apply that to every label:

.standard_label_style, label {
/* styles... */
}

This will affect every label through the site, so use with caution!

In your css file, can't you just put

.standard_label_style, label
{
 //styles
}
.standard_label_style, label {
    /* stuff */
}

I'm not sure you can... one possible workaround (feels a bit hackish though) is to attach the style to your body tag, then change the css to be this:

body.standard_label_style label{
   //Your styles here
}

One of the most underused CSS tricks of all time: Give your bodies an id or class!

HTML:

<body id="standard_label_style">
    <label>Hey!</label>
</body>

CSS:

#standard_label_style label{
    the styles
}

will take the styles, while

HTML:

 <body id="custom_label_style">
     <label>Custom!</label>
 </body>

Will not.

ninjagecko

You are dealing here with CSS precedence. Declarations which are "more vague" (body tag, classes) are applied before declarations which are "less vague" (specific elements, inline CSS).

Thus your answer depends on how the stylesheet is defining label styles. If for example it says label {...}, then that's fairly specific, and your best bet is to use a more specific CSS style, see:

The level of "specificity" you need to override, as I said, depend on how specific your other stylesheet was. According to the link, "CSS embedded in the html always come after external stylesheets regardless of the order in the html".

There is also a chance that if you yourself define label {your custom css} that should work, if you import your stylesheet afterwards. It is what I would try first to see if it works. Have you tried this? What was the result?

Note that if you want to completely override the other stylesheet, you will need to also reset any CSS you are not using by settings its values to inherit or as appropriate.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!