0

If I have a css file, mystyle.css:

body {
font-family: OpenSans, Arial, sans-serif;
font-size: 14px;
}

.news {
width: 800px;
background-color: #99EBFF;
}

but I wanted to override it for a specific part of the site for (in another CSS file, for example, cms-news-pages.css), e.g.:

.news {
padding: 2.5px;
width: 600px;
background-color: #FFE6B3 !important;
}

what would be a preferable alternative to !important for a class without getting into too much code spaghetti?

If anyone could advise me I'd be grateful for this, trying to make cleaner CSS coding.

avenas8808
  • 1,639
  • 3
  • 20
  • 33
  • CSS prioritises by specificity so you could just do ```body .news {...}``` and it should override just ```.news``` also make sure to include your custom css file after the default one – justrusty Jul 20 '20 at 10:45
  • a solution is to put your new CSS code underr the old one and it gets overwritten its called CASCADING syle sheet. it goes from top to bottom – bill.gates Jul 20 '20 at 10:45
  • if you just want a specific news container to be different, give it an id and style the id - it will override the class (and is more efficient than adding a parent selector) – Pete Jul 20 '20 at 10:47
  • @Pete yea, typo – bill.gates Jul 20 '20 at 10:50
  • You're right that `!important` is like a cheat-mode for CSS and it's not really advisable to use it in production. Normally the tools available for you to enable style overrides are: - specificity - the cascade order If you rely on the cascade order too much things can get difficult to debug, so in this situation, I'd use specificity. – Rounin Jul 20 '20 at 10:50
  • **Working Example:** .news { width: 800px; background-color: #99EBFF; } .news.news-page { padding: 2.5px; width: 600px; background-color: #FFE6B3 !important; }

    News

    This is the news.

    News on News Page

    This is the news on a dedicated news page.

    – Rounin Jul 20 '20 at 10:50

1 Answers1

2

Try to give more prefrence using parent selectors

Suppose .news has parent with classname .news-container

Then you can use

.news-container .news {
    background-color: #FFE6B3;
}

This will override css property of the .news.

Kiran Shinde
  • 5,732
  • 4
  • 24
  • 41