Why are my CSS properties being overridden/ignored? - css

I'm having some issues with the CSS "hierarchy" (not sure if it's proper to call it a hierarchy). I'm trying to style the below bit of HTML.
<body>
<section id="content">
<article>
<ul class="posts-list">
<li class="post-item">
<h2>[post title]</h2>
<p class="item-description">...</p>
<p class="item-meta">...</p>
</li>
...
</ul>
</article>
</section>
</body>
Since section#content changes on every page I have, I wanted to maintain consistent styles across all of them, so I wrote some "global" CSS rules.
#content {
color: #000;
margin-left: 300px;
max-width: 620px;
padding: 0px 10px;
position: relative;
}
#content p,
#content li {
color: #111;
font: 16px / 24px serif;
}
I wanted to style HTML within a ul.posts-list differently, so I wrote these rules.
li.post-item > * {
margin: 0px;
}
.item-description {
color: #FFF;
}
.item-meta {
color: #666;
}
However, I ran into some issues. Here is how Chrome is rendering the CSS:
For some reason, the rules #content p, #content li are overriding my rules for .item-description and .item-meta. My impression was that class/id names are considered specific and thus higher priority. However, it seems that I have a misunderstanding of how CSS works. What am I doing wrong here?
Edit: Also, where can I read up more about how this hierarchy works?

Elements id have the priority in CSS since they are the most specific.
You just have to use the id:
#content li.post-item > * {
margin: 0px;
}
#content .item-description {
color: #FFF;
}
#content .item-meta {
color: #666;
}
Basically id have the priority on class which the priority on tags(p,li,ul, h1...). To override the rule, just make sure you have the priority ;)

The "hierarchy" in which CSS rules are measured is called specificity. Each part of a CSS rule has an actual numerical base-10 value. IDs are worth 100 while classes are only 10.
For more information see http://coding.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/

Targeting ID's is more specific than targeting classes. More specific styling will overwrite less specific styling. It should be noted that in-line styling in HTML is more specific and will therefore overwrite ID-targeted styling. In other words:
<p style="color:white" id="itemDescId" class="item-description">...</p>
With the CSS:
p{color:blue;}
#itemDescId{color:red;}
.item-description{color:green}
The text will appear white - not because it's closest to the html code, but because it's higher in the specificity hierarchy. If you remove the inline styling (and you normally should for cleaner more manageable code), then the text would become red. Remove the ID and it will be green. And finally it will be blue once the class is removed.
This is one of the more complex topics to understand in CSS, and I'm only scratching the surface, but the easiest description I've found on how CSS specificity works is over at CSS tricks:
http://css-tricks.com/specifics-on-css-specificity/

My response should have been a "comment" on the answer, but I have the correct fix although #tibo answered correctly:
li.post-item > * {
margin: 0px !important;
}
.item-description {
color: #FFF !important;
}
.item-meta {
color: #666 !important;
}
The !important rule will override the order of evaluation between id and class.
Here is a link to an article, When Using !important is The Right Choice, that will help you to understand... it made my life easier :)

Better to follow the CSS standards.
choose css selector and makeit under its parent then u may not to get conflicts when loading css fles (like .css files)

Related

Set customized css as top priority

I hava a customized costom_css.css to overwrite others
blockquote {
font-size: 14px !important;
}
.pagination>.active>a {
background-color: orange !important;
border-color: orange !important;
}
I have to append !important to every single line,
Could this operation be implemented in one place?
Rather than using !important, which is notoriously bad practice and makes your codebase almost unmaintainable, you should add specificity to your selectors instead. Prepending your selectors with body should product more specificity to your selectors:
body blockquote {
font-size: 14px;
}
body .pagination > .active > a {
background-color: orange;
border-color: orange;
}
MDN has a great article on CSS specificity, check it out.
It's also worth noting that you should include your own CSS files (or code) after any external CSS files to ensure that they cascade correctly.

How to create css classes from existing ones? [duplicate]

Is it possible to make a CSS class that "inherits" from another CSS class (or more than one).
For example, say we had:
.something { display:inline }
.else { background:red }
What I'd like to do is something like this:
.composite
{
.something;
.else
}
where the ".composite" class would both display inline and have a red background
There are tools like LESS, which allow you to compose CSS at a higher level of abstraction similar to what you describe.
Less calls these "Mixins"
Instead of
/* CSS */
#header {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}
#footer {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}
You could say
/* LESS */
.rounded_corners {
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
border-radius: 8px;
}
#header {
.rounded_corners;
}
#footer {
.rounded_corners;
}
You can add multiple classes to a single DOM element, e.g.
<div class="firstClass secondClass thirdclass fourthclass"></div>
Rules given in later classes (or which are more specific) override. So the fourthclass in that example kind of prevails.
Inheritance is not part of the CSS standard.
Yes, but not exactly with that syntax.
.composite,
.something { display:inline }
.composite,
.else { background:red }
Keep your common attributes together and assign specific (or override) attributes again.
/* ------------------------------------------------------------------------------ */
/* Headings */
/* ------------------------------------------------------------------------------ */
h1, h2, h3, h4
{
font-family : myfind-bold;
color : #4C4C4C;
display:inline-block;
width:900px;
text-align:left;
background-image: linear-gradient(0, #F4F4F4, #FEFEFE);/* IE6 & IE7 */
}
h1
{
font-size : 300%;
padding : 45px 40px 45px 0px;
}
h2
{
font-size : 200%;
padding : 30px 25px 30px 0px;
}
The SCSS way for the given example, would be something like:
.something {
display: inline
}
.else {
background: red
}
.composite {
#extend .something;
#extend .else;
}
More info, check the sass basics
An element can take multiple classes:
.classOne { font-weight: bold; }
.classTwo { font-famiy: verdana; }
<div class="classOne classTwo">
<p>I'm bold and verdana.</p>
</div>
And that's about as close as you're going to get unfortunately. I'd love to see this feature, along with class-aliases someday.
No you can't do something like
.composite
{
.something;
.else
}
This are no "class" names in the OO sense. .something and .else are just selectors nothing more.
But you can either specify two classes on an element
<div class="something else">...</div>
or you might look into another form of inheritance
.foo {
background-color: white;
color: black;
}
.bar {
background-color: inherit;
color: inherit;
font-weight: normal;
}
<div class="foo">
<p class="bar">Hello, world</p>
</div>
Where the paragraphs backgroundcolor and color are inherited from the settings in the enclosing div which is .foo styled. You might have to check the exact W3C specification. inherit is default for most properties anyway but not for all.
I ran into this same problem and ended up using a JQuery solution to make it seem like a class can inherit other classes.
<script>
$(function(){
$(".composite").addClass("something else");
});
</script>
This will find all elements with the class "composite" and add the classes "something" and "else" to the elements. So something like <div class="composite">...</div> will end up like so: <div class="composite something else">...</div>
You can do is this
CSS
.car {
font-weight: bold;
}
.benz {
background-color: blue;
}
.toyota {
background-color: white;
}
HTML
<div class="car benz">
<p>I'm bold and blue.</p>
</div>
<div class="car toyota">
<p>I'm bold and white.</p>
</div>
Don't forget:
div.something.else {
// will only style a div with both, not just one or the other
}
You can use the converse approach to achieve the same result - start from the composite and then remove styling using the unset keyword. For example, if you start with the following sample composition:
.composite {
color: red;
margin-left: 50px;
background-color: green
}
you can then increase selector specificity to selectively remove styles using unset:
.composite.no-color {
color: unset
}
.composite.no-margin-left {
margin-left: unset
}
.composite.no-background-color {
background-color: unset
}
Here is a JSFiddle demonstrating this approach.
One benefit of this approach is that because the specificity of the compound selectors is higher than the composite itself, you do not need all of the combinations of classes to achieve the desired results for multiple combinations:
/* Multi-unset compound selector combinations, such as the one that follows, ARE NOT NECESSARY because of the higher specificity of each individual compound selectors listed above. This keeps things simple. */
.composite.no-background-color.no-color.no-margin-left {
background-color: unset;
color: unset;
margin-left: unset
}
Furthermore, at 96% support for the unset keyword, browser coverage is excellent.
Perfect timing: I went from this question to my email, to find an article about Less, a Ruby library that among other things does this:
Since super looks just like footer, but with a different font, I'll use Less's class inclusion technique (they call it a mixin) to tell it to include these declarations too:
#super {
#footer;
font-family: cursive;
}
In Css file:
p.Title
{
font-family: Arial;
font-size: 16px;
}
p.SubTitle p.Title
{
font-size: 12px;
}
I realize this question is now very old but, here goes nothin!
If the intent is to add a single class that implies the properties of multiple classes, as a native solution, I would recommend using JavaScript/jQuery (jQuery is really not necessary but certainly useful)
If you have, for instance .umbrellaClass that "inherits" from .baseClass1 and .baseClass2 you could have some JavaScript that fires on ready.
$(".umbrellaClass").addClass("baseClass1");
$(".umbrellaClass").addClass("baseClass2");
Now all elements of .umbrellaClass will have all the properties of both .baseClasss. Note that, like OOP inheritance, .umbrellaClass may or may not have its own properties.
The only caveat here is to consider whether there are elements being dynamically created that won't exist when this code fires, but there are simple ways around that as well.
Sucks css doesn't have native inheritance, though.
Unfortunately, CSS does not provide 'inheritance' in the way that programming languages like C++, C# or Java do. You can't declare a CSS class an then extend it with another CSS class.
However, you can apply more than a single class to an tag in your markup ... in which case there is a sophisticated set of rules that determine which actual styles will get applied by the browser.
<span class="styleA styleB"> ... </span>
CSS will look for all the styles that can be applied based on what your markup, and combine the CSS styles from those multiple rules together.
Typically, the styles are merged, but when conflicts arise, the later declared style will generally win (unless the !important attribute is specified on one of the styles, in which case that wins). Also, styles applied directly to an HTML element take precedence over CSS class styles.
Don't think of css classes as object oriented classes, think of them as merely a tool among other selectors to specify which attribute classes an html element is styled by. Think of everything between the braces as the attribute class, and selectors on the left-hand side tell the elements they select to inherit attributes from the attribute class. Example:
.foo, .bar { font-weight : bold; font-size : 2em; /* attribute class A */}
.foo { color : green; /* attribute class B */}
When an element is given the attribute class="foo", it is useful to think of it not as inheriting attributes from class .foo, but from attribute class A and attribute class B. I.e., the inheritance graph is one level deep, with elements deriving from attribute classes, and the selectors specifying where the edges go, and determining precedence when there are competing attributes (similar to method resolution order).
The practical implication for programming is this. Say you have the style sheet given above, and want to add a new class .baz, where it should have the same font-size as .foo. The naive solution would be this:
.foo, .bar { font-weight : bold; font-size : 2em; /* attribute class A */}
.foo { color : green; /* attribute class B */}
.baz { font-size : 2em; /* attribute class C, hidden dependency! */}
Any time I have to type something twice I get so mad! Not only do I have to write it twice, now I have no way of programatically indicating that .foo and .baz should have the same font-size, and I've created a hidden dependency! My above paradigm would suggest that I should abstract out the font-size attribute from attribute class A:
.foo, .bar, .baz { font-size : 2em; /* attribute base class for A */}
.foo, .bar { font-weight : bold; /* attribute class A */}
.foo { color : green; /* attribute class B */}
The main complaint here is that now I have to retype every selector from attribute class A again to specify that the elements they should select should also inherit attributes from attribute base class A. Still, the alternatives are to have to remember to edit every attribute class where there are hidden dependencies each time something changes, or to use a third party tool. The first option makes god laugh, the second makes me want to kill myself.
That's not possible in CSS.
The only thing supported in CSS is being more specific than another rule:
span { display:inline }
span.myclass { background: red }
A span with class "myclass" will have both properties.
Another way is by specifying two classes:
<div class="something else">...</div>
The style of "else" will override (or add) the style of "something"
As others have said, you can add multiple classes to an element.
But that's not really the point. I get your question about inheritance. The real point is that inheritance in CSS is done not through classes, but through element hierarchies. So to model inherited traits you need to apply them to different levels of elements in the DOM.
While direct inheritance isn't possible.
It is possible to use a class (or id) for a parent tag and then use CSS combinators to alter child tag behaviour from it's heirarchy.
p.test{background-color:rgba(55,55,55,0.1);}
p.test > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
p.test > span > span > span > span > span > span > span > span{background-color:rgba(55,55,55,0.1);}
<p class="test"><span>One <span>possible <span>solution <span>is <span>using <span>multiple <span>nested <span>tags</span></span></span></span></span></span></span></span></p>
I wouldn't suggest using so many spans like the example, however it's just a proof of concept. There are still many bugs that can arise when trying to apply CSS in this manner. (For example altering text-decoration types).
I was looking for that like crazy too and I just figured it out by trying different things :P... Well you can do it like that:
composite.something, composite.else
{
blblalba
}
It suddenly worked for me :)
In specific circumstances you can do a "soft" inheritance:
.composite
{
display:inherit;
background:inherit;
}
.something { display:inline }
.else { background:red }
This only works if you are adding the .composite class to a child element. It is "soft" inheritance because any values not specified in .composite are not inherited obviously. Keep in mind it would still be less characters to simply write "inline" and "red" instead of "inherit".
Here is a list of properties and whether or not they do this automatically:
https://www.w3.org/TR/CSS21/propidx.html
Less and Sass are CSS pre-processors which extend CSS language in valuable ways. Just one of many improvements they offer is just the option you're looking for. There are some very good answers with Less and I will add Sass solution.
Sass has extend option which allows one class to be fully extended to another one. More about extend you can read in this article
I think this one is a better solution:
[class*=“button-“] {
/* base button properties */
}
.button-primary { ... }
.button-plain { ... }
Actually what you're asking for exists - however it's done as add-on modules. Check out this question on Better CSS in .NET for examples.
Check out Larsenal's answer on using LESS to get an idea of what these add-ons do.
CSS doesn't really do what you're asking. If you want to write rules with that composite idea in mind, you may want to check out compass. It's a stylesheet framework which looks similar to the already mentioned Less.
It lets you do mixins and all that good business.
For those who are not satisfied with the mentioned (excellent) posts, you can use your programming skills to make a variable (PHP or whichever) and have it store the multiple class names.
That's the best hack I could come up with.
<style>
.red { color: red; }
.bold { font-weight: bold; }
</style>
<? define('DANGERTEXT','red bold'); ?>
Then apply the global variable to the element you desire rather than the class names themselves
<span class="<?=DANGERTEXT?>"> Le Champion est Ici </span>
Have a look at CSS compose:
https://bambielli.com/til/2017-08-11-css-modules-composes/
according to them:
.serif-font {
font-family: Georgia, serif;
}
.display {
composes: serif-font;
font-size: 30px;
line-height: 35px;
}
I use it in my react project.
If you want a more powerful text preprocessor than LESS, check out PPWizard:
http://dennisbareis.com/ppwizard.htm
Warning the website is truly hideous and there's a small learning curve, but it's perfect for building both CSS and HTML code via macros. I've never understood why more web coders don't use it.
You can achieve what you want if you preprocess your .css files through php.
...
$something='color:red;'
$else='display:inline;';
echo '.something {'. $something .'}';
echo '.else {'. $something .'}';
echo '.somethingelse {'. $something .$else '}';
...

Overwriting default bootstrap css with custom CSS only works with !important rule

basically I have already solved my problem, but I would like to understand why I needed to do it how I did it. Therefore I created a short example, available at https://jsfiddle.net/herbert_hinterberger/9x22u934/
Now I wanted to ask why I need to use the !important rule inside
.navbar-brand {
color: #eae8e8 !important;
}
to change the color of .navbar-brand? As of my understanding the custom CSS should overwrite the bootstrap default css rules. But for any reason the bootstrap default CSS rules are applied before the custom CSS rules if I do not use the !important rule. See
Can anybody please explain why I need to use here the !important rule?
Best regards,
Herbert
You don't need to use the !important every time.
The rule is, whatever css comes later is taken. So, if you have
.aClass {
color:red;
}
in red.css
and
.aClass {
color:blue;
}
in blue.css,
and you include blue.css after red.css, the text having aClass will be blue.
You only use !important when you want one rule to override everything else.
Edit: After the OP's comment, the actual answer to this question is this.
In the bootstrap.css file, we have something like:
.navbar-default .navbar-brand {
color: #hashtag;
}
therefore, when you do:
.navbar-brand {
color: #newHashtag;
}
it doesn't change the color of .navbar-brand that is invoked by .navbar-default (You use this class through .navbar-default in your HTML). Here, .navbar-brand is a descendant of .navbar-default. But, when you put in the !important, it tells all .navbar-brands to change color.
So, if you do want to change the color of your .navbar-brand, try something like:
.navbar-default .navbar-brand {
color: #newHashtag;
}
For more information, read up on descendant selector combinators in CSS.
When you want to overwrite bootstrap CSS with your own, you need to include your custom CSS after bootstrap.
<head>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/custom.css">
</head>
This is because the css selector bootstrap is using '.navbar-header .navbar-brand' has more specificity than yours '.navbar-brand'
see this http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
and try this
.navbar-header .navbar-brand {
color: #eae8e8;
}
Here is the best explanation for your Question
CASE: 1
<!-- HTML -->
<div class="blue box"></div>
/*CSS*/
div {
height: 200px;
width: 200px;
}
/*The Battle*/
.blue {
background-color: blue;
}
.box {
background-color: red;
}
In the Battle how wins? obviously last one i.e
.box {
background-color: red;
}
Background color red applied to div
Other Anwsers explain this case, writing custom css file after the bootstrap.css, it override bootstrap Styles
CASE: 2
ID vs. Class
<!-- HTML -->
<div class="box" id="box"></div>
/*CSS*/
div {
height: 200px;
width: 200px;
}
/*The Battle*/
#box {
background-color: blue;
}
.box {
background-color: red;
}
How Wins? obviously id Win, Id is declared as winner according to Rules of Specificity
Scores of elements according to specificity
inline-style = 1000 points (decided by css Specificity)
ID’s are worth a 100 points.
Classes are worth 10 points.
Elements are worth 1 point.
Example:
#content .sidebar .module li a{}
Score is :
#content =100; .sidebar, .module = 10 +10; li, a = 1+1
Total: 122
If we add one id at front as below We can overrides above mentioned style because the score of below mentioned style is 222
#main-container #content .sidebar .module li a{}

Including styles within another style

So I have been pondering about this and I don't think this exists. I also understand that my logic my be counter with what stylesheets are trying to accommodate, but let's give it a go:
Take the following example:
// Example "template style"
.blue_bold {
color: blue;
font-weight: bold;
/* other styles can go here */
}
So let's say I want to add that to my footer I would in my HTML go:
<div class="blue_bold" id="footer">
// Content goes here
</div>
This is perfect, but what if I want to add that element to a number of my elements. Say I want to add it to my navigation as well, I would then have to add that class to each element:
<div class="blue_bold" id="navigation">
// Content
</div>
....
<div class="blue_bold" id="footer">
// Content
</div>
My question is, as appose to declaring it via a class or style, is there no way to "attach" the style to another style within my stylesheet? (as example:)
#navigation, #footer {
attach_style(".blue_bold");
}
That way I can minimize my code by creating "base styles" and then attach those styles to individual styles within my stylesheet? This is again just a question, not something I wish to impliment, but I figure that given the above it would be a "nice to have" for people working with say brand guideline documents and want to attach specific styles to individual styles without going to the html to do it.
Any ideas? Does this exists?
You can't do it with pure CSS. You'll need to use LESS, or SASS/SCSS to generate your CSS.
Syntax examples here :
LESS
.blue_bold {
color: blue;
font-weight: bold;
}
#navigation,
#footer {
.blue_bold;
}
SCSS
.blue_bold {
color: blue;
font-weight: bold;
}
#navigation,
#footer {
#extend .blue_bold;
}
you will need to have a look on sass or less they are your best options.
sass here
less here
You can use sass or less but a more basic slight workaround is just to list the elements in your css like so:
#navigation,
#footer,
.some-other-element,
.another-element
{
// css styles go here that you want to apply to each element listed above
}
Can't see any benefits. What you're asking for is not a standard CSS.
You can define this for all elements with class blue_bold
.blue_bold {
color: blue;
font-weight: bold;
/* other styles can go here */
}
For this block
<div class="blue_bold" id="navigation"></div>
You can simply add another declaration like this:
#navigation, #footer {
background: black;
color: red;
}
Everything from .blue_bold will be used unless overwritten. What's wrong about it?

Can you scope CSS files so that they only apply to the descendants of a given element?

Given a css file, is there a way to scope the entire file so that it only applies to elements within a given element:
e.g. given:
<div id="container">
<span class="some_element"/>
<!-- etc -->
</div>
Is there a way to scope an entire css file to apply to all elements within "container" without prepending #container to every single css clause?
I’m afraid not. Some CSS pre-processors allow you to write code that achieves the same thing though.
E.g. LESS implements nested rules:
/* This LESS code... */
#header {
h1 {
font-size: 26px;
font-weight: bold;
}
p { font-size: 12px;
a { text-decoration: none;
&:hover { border-width: 1px }
}
}
}
/* ...produces this CSS */
#header h1 {
font-size: 26px;
font-weight: bold;
}
#header p {
font-size: 12px;
}
#header p a {
text-decoration: none;
}
#header p a:hover {
border-width: 1px;
}
And Andy mentioned SASS, which does the same thing.
You can use the scoped attribute on a <style> element, although there's little to no browser support for it. In your example:
<div id="container">
<style scoped>.some_element{}</style>
<span class="some_element"></span>
</div>
Here's a jQuery Polyfill: http://thingsinjars.com/post/360/scoped-style/
There are 2 ways you could approach this:
1) In HTML5, (not widely supported yet) there is to be a scoped attribute you can put on a <style> tag. Here is a brief article on the subject.
2) You could use a dynamic stylesheet language (like LESS or SASS) that allow you to nest related CSS rules together.
Not with CSS alone, but you can use Sass, which compiled into CSS.
You could use BEM naming notation -- http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/ ("block, element, modifier").
Your example would become:
<div id="container">
<span class="container__some_element"/>
<!-- etc -->
</div>
Yes, if you don't use an abbreviation, you're writing the same number of characters in your CSS... but your styles will have less specificity -- which can be beneficial.
Hopefully browser support for <style scoped> will get better in the coming years!
You could load the page in with php and throw whatever tag you want in dynamically, or do the same with javascript/jQuery... although that's fairly clumsy. There's no built in method to do this as CSS is always applied to the entire page.

Resources