de3
de3

Reputation: 2000

Overriding properties in CSS

#iddiv span {
    display: inline-block;
    width: 190px;
}
.myclass {
    width:10px;
}

Then I have

<div id="iddiv">
    <span>hello:</span> 
    <span class="myclass">yeah</span> <br/>
</div>

I would like the first span's width to be 190px, and second's to be 10px. But both are 190px: why it's not overriding the width propoerty?

EDIT: Thanks for your responses. What about unsetting width? I don't want 10px width, just default width as if it was undefined

Upvotes: 16

Views: 49804

Answers (6)

woodykiddy
woodykiddy

Reputation: 6455

Remember to use the keyword, !important, which functions to overwrite parent rules.

Also you can define your "myclass" in the following way:

#iddiv span.myclass {
    width:10px;
}

Upvotes: 2

Kon
Kon

Reputation: 27441

First of all, I'd suggest you properly target your selectors, as others are suggesting.

But when all else fails, you can use !important.

Upvotes: 1

Eric
Eric

Reputation: 97661

You could always use the !important flag to override:

.myclass {
    width: 10px !important;
}

Upvotes: 34

Jason Gennaro
Jason Gennaro

Reputation: 34863

It's not working because the first style is more specific.

To fix it, make sure you target the second span more directly, like this

#iddiv span.myclass

http://jsfiddle.net/jasongennaro/5fe9A/

Upvotes: 1

JohnP
JohnP

Reputation: 50029

CSS applies styles according to the specificity of the selectors

#iddiv span is more specific than myclass. Changing it to #iddiv .myclass should fix the issue for you.

Here's an article that goes more in depth about this : http://htmldog.com/guides/cssadvanced/specificity/

Upvotes: 5

RwwL
RwwL

Reputation: 3308

Because id+selector (#iddiv span) is more specific than a class. Either

#iddiv span.myclass

or

#iddiv .myclass

should work for this case.

Learn more about CSS specificity here or by Googling it.

Upvotes: 10

Related Questions