2

What is so annoying about CSS when you add style in the css class, it may apply other element/class by itself.

What the best way to prevent that?

For example:

HTML:

<div class='main-content'>
    <p> Hello World </p> 
    <span> Test One </span>
    <div class='column'>
        <span> Test Two</span>
    </div> 
</div>

CSS:

.main-content span {
    background: #921192;
    color: white;
    padding: 3px 4px;
    margin: 0 5px;
}


.column  span {
    font-size:20px;
    text-transform:none;
    display:inline-block;
}​

I do not want "Test Two" <span> to have a background color.

Test: http://jsfiddle.net/szm9c/1/

2
  • 1
    Unfortunately, it is not possible to not inherit in CSS. If you don't want a specific span to not not have certain styles, you'll have to target it specifically and override the styles, or you'll have to target other spans (with a class, for example) and apply the styles to them. Commented Apr 28, 2012 at 18:22
  • 1
    @NADH the problem the OP describes is not actually a style inheritance problem, just a selector one. Commented Apr 28, 2012 at 18:23

5 Answers 5

6

Use a selector that actually selects the elements you want. In this case >, the child selector, will suffice.

.main-content > span {
    background: #921192;
    color: white;
    padding: 3px 4px;
    margin: 0 5px;
}

http://jsfiddle.net/mattball/mQFz2/

Sign up to request clarification or add additional context in comments.

1 Comment

but I think this question can have more general answer. Its better to use classes...
2

Use .main-content > span, that selects only directly descendent elements.

Comments

2

This has nothing to do with inheritance.

To use CSS properly, assign properties to elements using selectors that match only the elements that you wish to affect. (The example given is far too artificial for a useful analysis and for constructive suggestions on a better approach.)

Comments

0

You can use this

.main-content > span {
background: #921192;
color: white;
padding: 3px 4px;
margin: 0 5px;
}

If you use like .main-content > span that style will only affect to the immediate child spans of .main-content class

Comments

0

Just use all: initial at your root element.

.selector 
{
    all: initial;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.