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.
Related
I have a clear:both written for an html tag and I want to undo it at a particular location. Please guide me if this is possible. If possible then how? Thanks.
img{
clear:both;
}
Now I want to remove the clear:both for a img tag I am placing.
To "undo" in CSS terms means for the rule to be more specific than the one you're trying to overrule. To do that for an inline style attribute you'll need to use an !important exception, such as:
<selector> {
clear: none !important;
}
However, using !important is not recommended as good practice:
Using !important is bad practice because it makes debugging hard since
you break the natural cascading in your stylesheets.
It often implies that you're not properly implementing (or understanding) specificity.
In larger projects you'll often see this used on classes such as .hidden where the semantics of the class are obvious, and you don't want them to be burdened by the normal rules of specificity.
First add an id next to the specific image or a class if many
<img src="https://../x.jpg" alt="" id="thisOne" class="thoseOnes">
Then in your css:
img#thisOne {
clear:none;
}
or
img.thoseOnes {
clear:none;
}
When I want to define css selector with :hover and :active I have to do:
#mainPage #content div.group:hover, #mainPage #content div.group:active {}
As one can see it contians repeated #mainPage #content div.group and can get messy. Is there a way to group it somehow like:
#mainPage #content div.group:hover:active {}
In pure CSS there is not much of a better way to handle both more succinctly without adding a class or ids.
You could consider a CSS pre-compiler (like LESS or SASS/SCSS).
In LESS or SCSS:
#mainPage #content div.group {
&:hover, &:active {
color: red;
}
}
I suggest add ID for the element has class group and write below code will reduce the effort:
#idname.group:hover, #idname.group:active{}
Is there a reason why you're using #mainPage #content before div.group?
Generally, it's not necessary to add that much 'specificity' to your selectors - it's better to instead, have unique classes. So make sure that the class .group is only used for elements that you want to have the same styles.
If you do that, you should be able to style those elements just using
.group { styles here}
You might run into an issue now where if you try to override any of the styles you set like #mainPage #content, those will be more specific and so in effect 'stronger' than styles where you don't use the full list of parents. If possible, change all your styles not to include the parent elements - this is also worthwhile in case you ever want to move an object to a different part of the html!
It's also, in general, advisable not to use id's (#name) to attach css styles - if possible, just use classes. Unless you're doing javascript, you shouldn't have much need for id's.
Obviously there exceptions to the above, and for all I know you may have a perfectly good reason for doing things the way you have - in which case SASS (as suggested in a few other answers) is a good solution for you.
If not useful for you, I hope at least this answer might be useful for someone who might come along later - I've noticed that a lot of people newer to css don't realize how specificity of selectors works and end up making their styles a lot more complicated than necessary as a result! :)
Old question, but this should be relevant for somebody who needs this.
Pseudo-class released by the end of 2020
You can use :is() pseudo-class like so :
#mainPage #content div.group:is(:hover, :active) {
}
Here is a little snippet to picture it :
a:is(:hover, :focus) {
color: red;
outline: #5bc8ea dotted 4px;
outline-offset: 4px;
font-weight: 600;
}
Hover/Focus me
More informations about :is() pseudo class here: https://developer.mozilla.org/en-US/docs/Web/CSS/:is and here: https://css-tricks.com/almanac/selectors/i/is/.
Works with most of the popular browsers (incompatible with IE, Opera and Safari < 14) https://caniuse.com/css-matches-pseudo.
It surely is more often used to select elements than pseudo-classes like :hover or :focus but it will do the trick as I can't see any other solution for now.
Why you use #mainPage #content? #content should be enough to find the div your looking for without the #mainPage.
Also id's are only allowed to be used once and not in multiple places like classes are. Id's are usually reserved for script assignments and not CSS. I would do
#content .group:hover{}
#content .group:active{}
if i understood correctly, you want a group of elements to act a certain way? manipulate the parent class then.
.parent-class:hover {
.child-class {
…desired styles go here
}
}
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.
I have created a web widget. That my client put in their websites. Basically on load it calls webservice and loads data specific to client.
As a result it looks like:
<div class="widget">
<div class="container">
</div>
</div>
Dynamically I apply CSS styles to my widget class. To look consistent with our corporate styling.
The problem is when client application styles overwrite the style I applied run time.
For example if client has, it overwrites my styles:
body {
margin: 0 auto;
padding: 0;
width: 90%;
font: 70%/1.4 Verdana, Georgia, Times, "Times New Roman";
}
Is there any way to break inheritance? Just to say whatever div with class widget styles has do not inherit parent styles.
I don't think you can break CSS inheritance per se, but you can try to circumvent it by following the rules of CSS specificity. Here's a good article about Specificity.
As a last resort, try adding !important to styles in the widget to give it a higher specificity than the default styles.
#myWidget{
font: 100%/1 "Times New Roman", Serif !important;
}
If the client is also using !important it could cause problems. If you could setup a jsFiddle with an example, we could help find the issue.
Note, going the route of adding !important should be a last resort as it's the 'nuclear option' of style specificity.
You can not force elements to NOT inherit parent styles.
You can however override all possible styles that you do not want changed. If your CSS specificity is higher than the customers specificity then your styles will be dominate/expressed on the page.
See:
CSS Specificity via css-tricks.com
Per your example using the code below would be more specific than the body declaration and thus override :
.widget .container {
font-family: Arial;
}
You can't break style inheritance as such, but you can ensure that your styles are either more important or loaded in the right order so yours comes out on top.
Have a look at the !important tag.
Alternatively if you load your stylesheets after theirs yours will take precedent (unless theirs is inline). You can use Javascript to load your styles after the body has loaded (But then you'd get a "flicker" effect).
You could also try inline styling. Inline styling has the highest priority. This will work if client overrides use an imported stylesheet.
Like others have mentioned, another option is !important.
You can also read up the relevant specs at http://www.w3.org/TR/CSS2/cascade.html where they describe exactly how they cascade. If above mentioned tricks don't work, perhaps specs will give you a clue or you will know for certain that this is not possible.
Use of the !important css attribute is considered a bad practice. Because it introduces the potential for precedence conflicts, and makes it extremely difficult to troubleshoot css in the long run.
A less intrusive approach to this problem is to delimit your widget with an id, and in your stylesheet, to reset some of the most important style declarations using the "universal" selector, such as:
#myWidget *{
margin: 0;
padding: 0;
background: none;
border: none;
}
For example. Then, define your overrides specifically.
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.