开发者

Can I give a whole set of styles supreme importance over other style declarations?

开发者 https://www.devze.com 2023-04-06 15:03 出处:网络
Is it possible to give a whole set of styles supreme importance? Ie, early on you might have the following default css:

Is it possible to give a whole set of styles supreme importance?

Ie, early on you might have the following default css:

<link rel="stylesheet" href="/style.css" type="text/css" media="screen" />

and inside it has

    body {
       background: #000;
    }

    h1 {
       color: #fff;
    }

But then(!) you decide to make things exciting and have some more css inside the tag that is the same but different:

<style type="text/css">
    body {
       background: #fff;
    }

    h1 {
       color: #000;
开发者_如何学运维    }
</style>

For whatever reason, the styles inside style.css that are linked in take importance over the ones I'm putting in statically.

What I'd like to know is, is there a way of umbrella'ing a whole bunch of styles so they take the highest importance? The best I know is

<style type="text/css">
    body {
       background: #fff !important;
    }

    h1 {
       color: #000 !important;
    }
</style>

Which starts to get a bit tedious if there are many styles.


add a single class to body, ie body class="stylecatcher" or whatever

then you can style (and override default styles) easily

<style type="text/css">
    body.stylecatcher {
       background: #fff;
    }

    .stylecatcher h1 {
       color: #000;
    }
</style>

I didn't find it to be a good practise to use the !important selector.


What you need is called specificity. From the w3 here and here and adobe link


Typically in CSS if you add a selector that is the same further down in the document, the one closest to the end (the highest line number) will be taken into effect.

<style type="text/css">
    body {
       background: #000;
    }

    h1 {
       color: #fff;
    }

    body {
       background: #fff;
    }

    h1 {
       color: #000;
    }
</style>

The background would be white and the font color black.

0

精彩评论

暂无评论...
验证码 换一张
取 消