understanding css important keyword in this example - css

in my html I have
<div id="mainNewsBody" class="news">
<a class="readMore" href="/News/Details/1">read more ...</a>
</div>
I tried to style read more ... snipper with this css
#mainNewsBody .news .readMore a{
color: #7F0609;
}
to actually apply this style I have to use !important keyword in color property.
I know that this !important keyword force to use that property but I do not understand why that is the case here, because I explicitly told to match on particular id with particular class element and inside that element to mach link.
Can someone englight me.
Thanks

Try this one:
.news .readMore {
color: #7F0609;
}
There's no need to call for id and class name for the same element.

It's a.readMore instead of .readMore a (the first case would search for an element with class .readMore and append the CSS to any children a-elements)
and #mainNewsBody .news should be #mainNewsBody.news (you should 'concatenate' the id and class since they refer to the same element)
making a total of #mainNewsBody.news a.readMore
Fiddle
EDIT
I see many notes on simplifying your css to just classes. This really depends on what you're trying to accomplish. If you're working with a huge CSS file, I'd recommend specifying as strict as possible. This to prevent any CSS being applied on places where you don't want it to.
a { } for example will mess with all your links, a.news { } will only mess with a class='news'

It'd the specificity which is troubling you, the more elements class id you have in your selector, more specific your selector is.
So for example
.class a {
}
is more specific than just
a {
}
Just see to it that you do not have a more specific selector, if you've than you need to make the current one more specific or use !important declaration as you stated.
In the above snippet this is incorrect
#mainNewsBody .news .readMore a
It will search for an element having class news inside an element having an id mainNewsBody which is not true in your case so either use this
#mainNewsBody a.readMore {
/* This will be more specific than the below one
as you are using id here and not class */
color: #7F0609;
}
Or use
.news a.readMore {
color: #7F0609;
}

Ozan is right, remove the "mainNewsBody" ID from the CSS if it's not absolutely necessary.
.news .readMore a{
color: #7F0609;}
If you want to be really specific and need to include the ID in the CSS selector remove the space from in-front of ".news"
#mainNewsBody.news .readMore a{
color: #7F0609;}
CSS Tricks - Multiple Class ID Selectors

CSS rules marked !important take precedence over later rules. !important ensures that this rule has precedence.

Probably your code is generating inline css for the a element, or you have another less specific definition for a element with !important keyword somewhere else.
Inline styles have priority higher than styles defined outside the element. To overcome the inline style or a style with !important keyword by a less specific definition, you need to define it by the keyword !important and a more specific definition.

Related

Make !important the whole .class selector

Is it possible to make the entire .class CSS selector important? I'm thinking in this kind of structure:
.custom-selector !important {
display: inline-block;
vertical-align: middle;
position: relative;
padding-left: 5px;
}
I don't know if it's possible.
No, it's not possible. !important is thought to be an instrument of last resort and as such should be used sparingly. !importanting whole selectors would caricature that idea.
If you need to trump other styles, use CSS specificity to your advantage. You can use, e.g., these techniques to push your style declarations to the top:
double class name will trump single class name:
.custom-selector.custom-selector > .custom-selector
ID trumps class:
#custom-id > .custom-class
IDs can be duplicated, too:
#id#id > #id
inline styles trump any stylesheets:
<style>
p#id#id.class.class { color: green; }
</style>
<p id="id" class="class" style="color:red">I am red!</p>
First off !important applies to one specific declaration in a CSS rule. It doesn't apply to a class. So, "no" you can't make a class !important.
Second off, !important is just one part of CSS specificity. You can also use other ways to make a rule be a more specific rule to have precedence (such as referring to an id in the parent chain instead of just the class. When I'm writing CSS, using !important is my last possible choice - I'd much rather solve overrides with other specificity solutions. Usually, if you control all the CSS, this is pretty easy to avoid using !important. If you have to override some CSS that you don't control, then sometimes it is handy.
Check this question here for more details. As it explains things better.

why space between form.validate and .ng-invalid-emal.ng-dirty

In an AngularJS application for stylesheet I don't understand where there is a space between "form.validate" and ".ng-invalid-email.ng-dirty":
<style>
form.validate .ng-invalid-required.ng-dirty {background-color: lightpink;}
form.validate .ng-invalid-email.ng-dirty {
background-color: lightgoldenrodyellow;
}
div.error { color: red; font-weight: bold;}
</style>
Any hint or help would be greatly appreciated it.
Those are css selectors.
form.validate is a selector for any form that has the .validate class on it. .ng-invalid-required.ng-dirty matches any element with both .ng-invalid-required and .ng-dirty classes on it.
It's the same as writing the following in a css file:
.class1.class2 {
color: #fff;
}
Angular will classes to elements that are in a certain state (invalid, valid, etc) and allow you to define how those states will be defined stylistically. Maybe you change the color, bold them, underline them, add an asterisk, etc. They're just hooks to simplify your life when using ng.
Because form.validate .ng-invalid-email.ng-dirty means something with both the ng-invalid-email class and the ng-dirty class on it that is inside a form with the validate class on it, which is what is wanted here.
Without the space it would select a form with all three of the validate, ng-invalid-email and ng-dirty classes on it.
The space indicates a descendant element within the selector syntax. This MDN page has more on that.

Can I set a default css class for an html element

If I define a css class, is there anyway to set that class as a default class for an html element? To clarify, I was hoping to factor out the definition of the class so it could be used by one or more css selectors or applied discreetly in the html.
For example:
.myclass {float:right}
h1 {class: myclass}
The above does not work of course, but hopefully you know what I am asking as I have not been able to find how to do this.
Not with standard CSS, but why not just do:
h1 {
float: right;
}
If I define a css class, is there anyway to set that class as a default class for an html element?
No. You can, however, select all elements and apply a rule to them:
* {
foo: bar;
}
You can do that if you are using a CSS processor like LESS (http://lesscss.org/#-mixins) or SASS (http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#mixins).
From your repeated comment “I was hoping to factor out the definition of the class so it could be used by one or more elements or applied discreetly”, it seems that what you are really up to is how to define a set of CSS declarations so that they apply to elements in a given class and and some elements independently of class. The way to do this is to use a list of selectors, e.g.
.myclass, h1 { float:right; /* and other declarations as needed */ }
This is the kind of “factoring out” that you can achieve in CSS. There is no way to “factor out” “CSS classes”, because there are no CSS classes. There are classes in HTML, and you can specify rules that apply to such classes.
Just write the following HTML
<h1 class="mylass"> .... </h1>
and write VALID CSS
i.e.
.myclass {float: right}
I'm not sure what you want to achieve, but maybe you ask this because you want to have multiple html elements use the same "class"?
If that's the case you can write it like this:
h1, h2, span{
background: red;
}

Is it possible to give one CSS class priority over another?

Say I have a div that uses two css classes that both use text-align, but one is centered and the other is right aligned.
Is it possible to specify something that will give one class priority over the other?
specify a more specific selector, eg prefix an ID before it or prefix the nodename before the class
assign it after the other class
if two classes are in separate files, import the priority file second
!important
!important is the lazy way, but you really should go for #1 to avoid important-ception. Once you've added one !important you can't use it to make some other rule even more important.
If you want to be explicit about it, you can specify how the combination of those two classes work together, by supplying a rule for elements that contain both classes. For instance, you can explicitly give something with both classes foo and bar the same styling as just bar as follows. This works because .foo.bar is more specific than just .foo for elements which have both classes, and thus this rule will take precedence over the .foo rule.
.foo { text-align: center }
.bar, .foo.bar { text-align: right }
If you don't want to be this explicit, you could just place the rule for bar after the rule for foo, as given selectors of the same specificity, later rules take precedence over earlier ones:
.foo { text-align: center }
.bar { text-align: right }
You can learn more about how precedence between rules is determined in the CSS specification chapter about the cascade; that's the "C" of CSS, and is important to understand well in order to take full advantage of CSS.
You should use CSS specificity to override previous declarations
http://htmldog.com/guides/cssadvanced/specificity/
p = 1 point
.column = 10 points
#wrap = 100 points
So:
p.column { text-align: right; }
can be overwritten by:
body p.column { text-align: left; }
as “meder omuraliev” has answered, you may use a more specified selector. and I would like to provider a general way that how to sepcific a higher priority for any type of selector, that is use the attr presdeo.
for example:
html body .foo { font-family: Arial !important;}
html body .bar[attr]{ font-family: Arial !important;}
to override this you may use like this:
html body .foo:not([NONE_EXISTS_ATTR]){ font-family: Consolas !important;}
html body .bar[attr]:not([NONE_EXISTS_ATTR]){ font-family: Consolas !important;}
To add to the other answers, you don't need to add selectors not related to what you originally wanted to increase specificity, the same can be achieved by repeating the same selector multiple times:
.foo.foo takes precedence over .foo, and .foo.foo.foo takes precedence over the previous ones.
This is better than adding non-related selectors, because you only select what you really want to select. Otherwise you might get unexpected behaviour when unrelated stuff you added changes.
.bar { text-align: right !important;}
use !important
Example :
p {
background-color: red !important;
}

Use HTML tag names, classes or IDs in CSS?

In designing the HTML and CSS for a page, when should I use
img.className
versus
.className
versus
#idName
or some other variant?
Are there guidelines or recommendations?
Summary from answers
Thank you to all answerers - there is some excellent stuff here!
make CSS as specific as possible
use an OO approach
order: #id, tag, tag.className, .className
when to use each selector, also class/ID comparison
give selectors names based on purpose, not what they look like
use advanced selectors for smaller code, leave CSS classes for exceptions/overrides only
manage ASP.NET munging ID
In general you should be as specific as the item demands.
There is no general rule, it depends on the style in question.
A lot of people will recommend you keep to the lowest specificity with the theory that this allows the maximum cascading reuse but this is absolutely toxic in real world situations where you have multiple developers all working on slightly different versions of what a .foo might look like. Pollution from inheritance you did not want leads to massive bloat in trying to undo that locally or time-loss in refactoring.
The best guideline I always offer is to try and think of CSS in OO terms: class selectors map to interfaces more or less, tags map to classes, and ID selectors map to instances. Consequently decide if the style you want to apply really applies to that thing, all things like it, or anything which wants it.
I also strongly encourage you to make use of high level IDs on wrapper elements so you can write selectors in a namespace like fashion (i.e. #foo .bar, #foo .baz where #foo is unique to a page or set of page designs) which allows you both a level of specificity which reduces cross-design pollution and a level of generality which lets you make the most of cascading CSS reuse.
Best of both worlds.
It depends on the intended semantics, and, as others said, be as specific as possible.
#idName for unique elements on the page. Good examples are #header and #footer
TAGNAME for general purpose page styling.
TAG.classname and .classname for exceptions/overrides to the above rules.
And don't forget the use of advanced selectors. A bad example:
<style>
H1{ font-size: 200%; color: #008; }
#mainMenu { color: #800; }
.in_the_menu { color: #800; font-size: 150%; }
</style>
<h1>Hello World!</h1>
<div id="mainMenu">
<h1 class="in_the_menu">My Menu</h1>
</div>
The same could have been achieved with:
<style>
H1{ font-size: 200%; color: #008; }
#mainMenu { color: #800; }
#mainMenu H1 { color: #800; font-size: 150%; }
</style>
<h1>Hello World!</h1>
<div id="mainMenu">
<h1>My Menu</h1>
</div>
The second example gets rid of the superflous "class" attribute on the H1 element in the "mainMenu" div. This has two important benefits:
The HTML code is smaller and cleaner
You are less likely to forget to add the class attribute
If you take good care of you CSS, and make use of proper advanced selectors, you can nearly completely leave out CSS classes. And keep them only for exceptions/overrides.
Take this example which draws boxes with headers:
#content H2{
border: 1px solid #008789;
padding: 0em 1em;
margin: 0.2em 0em;
margin-bottom: 1em;
font-size: 100%;
background: #cccb79
}
#content H2 + DIV{
margin-top: -1em;
border-left: 1px solid #008789;
border-right: 1px solid #008789;
border-bottom: 1px solid #008789;
margin-bottom: 1em;
}
Now, as soon as you follow a H2 with a DIV in the #content element, you have a nice box. other DIVs and H2s are left alone:
<div id="content">
<h2>Hello Box!</h2>
<div>Some text</div>
<div>Some more text</div>
<div>Some more text</div>
<h2>And another title</h2>
</div>
If you get these rules right, you hardly ever need classes, and can work with IDs and TAG names alone. And as an added bonus, your HTML will be a lot nicer to read and maintain.
You preference should be, in order from highest to lowest:
id
tag
tag.className
.className
ID selectors are fast. Tag selectors are reasonably fast. Pure class selectors are slow because the browser essentially has to interrogate every element and see if each has that class. Getting elements by ID or tag name are "native" operations from a browser's context.
Also, I find it good practice to make your CSS selectors as restrictive as possible otherwise it just turns into a mess and you end up getting all sorts of unintended consequences where CSS rules apply where you didn't otherwise expect, which often forces you to create a similar yet different selector just so none of the rules regarding the first don't apply (translating into more mess).
Basically if you know if you only use a class on div elements then do this
div.className
not
.className
If you apply a class to several elements just list them:
h1.selected, h2.selected, h3.selected
instead of
.selected
In practice I find very few situations where you need to use "naked" class selectors or where it is advisable to do so.
you should use the selector best describing your rules
id: when you want to select one single element
.classname: when you want to style elements regardless of their tag
tag.classname: when you want to style only tags with the given class
tag tag tag: when you want to style all subelements of a tag
Class selectors
.className
This is to be used when you have more than one element on the page that you would like to apply the same style to. It can be to any tag element. So in the following all will use the same style as set out by the .className.
<p class="className"></p>
<img src="/path/to/image.png" class="className" />
But you can also restrict it like so:
img.className
By placing the tag along with the style definition, you're saying that this style is only to be used when it's the class used by that particular tag, in this case, an image.
HTML code will look like this:
<img src="/path/to/image.png" class="className" />
If you have other elements on the page using the same class style, but are not of the same tag, then the styles set out in this will not be applied and they will take on the more generic version as mentioned in the first example.
So repeating the example above:
<p class="className"></p>
<img src="/path/to/image.png" class="className" />
Only the image will take on the style as set out by img.className whereas all the rest will take on the style rules set in .className.
ID selectors
#idName
This is to be used when there is only one instance of a particular element that you wish to apply the style to.
You can also force it to apply only in certain tag conditions as you have earlier with the class definitions.
p#idName
This example will only apply to the paragraph block marked with the ID:
<p id="idName">
If you were to put that id on another element, like this:
<div id="idName"></div>
Then it will not take on the style set out and be ignored.
As to your two first selectors, the first of the two will overwrite the second, as it's more specific. You can calculate the specificity of a selector.
One thing worth noting is that some server side scripting technologies (most notably ASP.NET) don't play well with using IDs for your styling. If there is a chance your design will be used with such a technology, I recommend forgetting about #id selectors and use tag.className instead.
The reason is that ASP.NET actually changes the ID that ends up in the HTML based on a number of criteria, if the tag is output by a server side control.
I know this is a pretty old question but for all those who are reading this just now...
There are 4 categories of rules in general:
ID Rules, Class Rules, Tag Rules, Universal Rules.
And it's important to mention that class selectors are faster than tag selectors. So you should always use them in the following order
1. ID Selector
2. Class Selector
3. Tag Selector
4. Universal Selectors
In your case you should never use the tag name before class name.
You can find more information here: Writing efficient CSS
It really depends on the situation:
.error{
color:red;
}
p.error{
background-color:yellow;
}
div.error{
background-color:grey;
}
Always use the cascading effect of CSS to your advantage.
It's good practise to use the least specific rules you can for each rule.
How you structure your CSS will depend on the particular needs of the design.
Yes. You may want to use the same classname for two elements in the future. Be explicit and clear. This will also prevent class-rules from overlapping onto unintended elements.
h1.title { font-size:18px; } /* My h1's are big */
p.title { font-size:16px; } /* My p's are smaller */
.title { color:#336699; } /* All titles are blue */
Use ID's only when necessary, and only once per page.
When to use what depends on what you want to select. img.className (type selector + class selector) selects only IMG elements that’s in the class “className” while .className (just class selector) selects any element that’s in that class and #idName (id selector) any element with the ID “idName”.
But besides that, the selector all have a differente specificity that affects the order in which the properties of that rules overwrite the one of others.
So if you have an IMG element with the ID “idName” that’s in the class “className”:
<img src="…" id="idName" class="className">
The properties of the rules would be applied in the following order (specificity from highest to lowest):
#idName
img.className
.className
But when you use a specific class only for one specific type of elements (e.g. “className” only for IMG element), you can go with only .className.

Resources