简体   繁体   English

CSS继承无法正常工作

[英]CSS Inheritance not working as expected

So I have html and css that looks like the following.. 所以我有html和css,如下所示。

    <div id="foo">
        <p> Foo text </p>
        <div id="bar">
            <p> Bar text </p>
        </div>
    </div>

And then I have some css that looks like the following... 然后我有一些看起来像下面的css ...

    #foo p {
    text-align:left;
    font-family: helvetica, verdana, sans;
    font-size: 14px;
    color: #000000;
    padding: 10px 10px 10px 10px;
    margin: 0px 0px 0px 0px;
    }
    #bar p {
    font-size: 12px;
    color: #ffffff;
    padding: 0px 0px 0px 0px;
    }

So isn't the point of CSS to override the styles applied to the child from the parent foo? 因此,CSS的目的不是要覆盖从父foo应用于子项的样式吗? It's not doing this, I just get the child styles overridden by the parent. 它不是这样做的,我只是让父级覆盖了子级样式。 I'm clearly missing something big here, any help would be great. 我显然在这里错过了一些重要的事情,任何帮助都会很棒。

I think you're confused, or have coded yourself blind. 我认为您很困惑,或者已将自己编码为盲人。 :) What you have works perfectly well, it is your intentions that I suspect is off. :)您所拥有的一切都运行良好,我怀疑您的意图不对。 What you're thinking is that the first set of styles should be inherited and then overwritten by the second, but if you look to your HTML, that's not the structure you've put in place. 您在想的是应该继承第一个样式集,然后再覆盖第二个样式集,但是如果您查看HTML,那不是您已采用的结构。

You're saying #foo's <p>'s should have the first style, but the second set of styles are in a <div> , and hence not applied. 您是说#foo's <p>'s应该具有第一种样式,但是第二组样式位于<div> ,因此适用。 The second p is in a <div> , and hence will not have the first rules which are for elements under a <p> . 第二个p在<div> ,因此将没有用于<p>下元素的第一条规则。

If you want the styles to inherit, wrap your <div> into your <p> (even though structurally not good, nor valid in a number of schemas); 如果希望样式继承,请将<div>包装 <p> (即使在结构上不好,在许多模式中也无效);

<div id="foo">
        <p> Foo text 
        <div id="bar">
            <p> Bar text </p>
        </div>
    </p>
</div>

I'm not sure what you're trying to do, though, so it's a bit hard to come up with good examples to solve your problem. 不过,我不确定您要做什么,因此想出好的例子来解决您的问题有点困难。 :) :)

Look Chris you're misunderstanding CSS selectors and their inheritance ... 克里斯,您误解了CSS选择器及其继承...

Nothing will explain it better than this presentation by Russ Weakly 没有什么比Russ Weakly的演讲更好地解释它了。

CSS Cascade CSS级联

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM