ajax333221
ajax333221

Reputation: 11764

Why this only works with "!important"?

I have this piece of code, that it refuses to work without the !important (which I never want to use, because I know there is always a way to do without it).

The interesting thing is that the CSS line is after everything else (and as far as I know, this should overwrite the other stuff)

live demo jsFiddle

HTML Structure:

<div id="body">
    <div class="box">
        <p>...</p>
    </div>
    <p>...</p>
</div>

CSS:

#body{
    padding:18px 35px;
}

#body p{
    margin-bottom:18px;
}

.box{
    background:#ddd;
    border:1px solid #000;
    padding:5px;
}

.box p{
    margin:0;/*works with !important*/
}

Upvotes: 0

Views: 122

Answers (3)

LoveAndCoding
LoveAndCoding

Reputation: 7947

Your #body p has a greater specificity value. You can read more on generally how specificity values are calculated here.

Upvotes: 0

MtnViewJohn
MtnViewJohn

Reputation: 683

Matching p with #body has higher specificity than matching p with .box. Read the specificity section of the CSS spec for help. Try

#header .box p { margin: 0; }

The space between #header and .box is important.

Upvotes: 2

Bryan Naegele
Bryan Naegele

Reputation: 660

It's because the ID of #body p is a more specific selector than the class of .box p. The important simply overrides that cascade.

Upvotes: 5

Related Questions