I have been forced to use !important in css. There is probably another way to get this done, but I am doing it because I only want a specific subset of an already styled class to have a different style. The situation is with jQuery's datepicker. In datepicker, I am setting certain days to have different priority colors. This end result is that the td element holding the <a> which holds the date gets the class name
.date-priority > a
{
background: url("") red;
border: 1px solid yellow;
}
However, this change gets overridden because there is a more specific rule for that anchor tag, it specifically has a class on it. I do not want to change all elements with that class, only to override a few of them. So, I decided to use !important in the previous definition
.date-priority > a
{
background: url("") red !important;
border: 1px solid yellow !important;
}
It works. But it just does not seem to be best practice. Is using !important a hack in general, and more specifically in this instance?
HTML:
<td onclick="
DP_jQuery_1348602012259.datepicker._selectDay('#date',8,2012, this);
return false;"
title="Available" class=" ui-datepicker-week-end date-priority">
29
</td>
If this is the case, just add a separate rule for those elements:
.date-priority > a,.date-priority > a.className {
background: url("") red;
border: 1px solid yellow;
}
Demo: http://jsfiddle.net/Blender/rCyjV/
The only reason !important is frowned upon is because it makes future additions to the CSS possibly frustrating.
Short anwser: no.
Long answer: !important is thought specifically for situations where you don't want a rule to be overridden by successive declarations. In addition, the "weight" assigned to the selectors (most specific = most important) is not always the behavior that a developer wants.
From W3C specs:
Both author and user style sheets may contain "!important"
declarations, and user "!important" rules override author "!important"
rules. This CSS feature improves accessibility of documents by giving
users with special requirements (large fonts, color combinations,
etc.) control over presentation.
So definitely it's not a hack :-)
Related
I have some CSS that colors a row on my table on hover.
tr:hover {
background: gray !important;
}
However, it also highlights the filter row on the table. So I did Inspect and find it has <tr class="MuiTableRow-root MuiTableRow-hover"...etc
So, my question is, how can I modify the above code so that it applies only to that class shown above?
Edit: First attempt at apply class.
.MuiTableRow-root MuiTableRow-hover {
tr:hover {
background: gray !important;
}
}
As pointed out in the comments, please take a look at the documentation for class selectors.
You are having trouble to combine the class with the element's tag.
In this case they are written together like this:
tr.MuiTableRow-hover:hover {
background: gray !important;
}
When the HTML tag has the class: Write the tag and . and then the class
When the HTML tag has some element inside with a certain class, separate them with a space
Do yourself a favor and search for CSS tutorials to teach you the basics. It's not very hard to learn if you can spare the time
A little bit advanced is trusting CSS Specificity and leaving out !important. If your selector is more specific (or your CSS was loaded later) your style will be applied even without use of !important.
tr.MuiTableRow-hover:hover {
background: gray;
}
The css rule should look like this:
tr.MuiTableRow-hover:hover {
background: gray !important;
}
Note that using !important is not best practice so better if you try to avoid it if possible
When we write our widgets using HTML, JavaScript, and CSS and package the widgets together as a library, we may have
.foobarwidget-sidebar-section .sub-section { border: 1px solid #000 }
so we will implement the JavaScript to work with the behavior of this widget that we defined, that can be used in any page on our website or by other people.
But then, if there is a user of this widget, and he has HTML in his own webpage for a "sub-section":
.sub-section { color: green }
Then pretty much his .sub-section will add to our widget's CSS style.
It is true that he can use
#the-main-content .sub-section { color: green }
or
.a-main-content-box .sub-section { color: green }
so that it doesn't affect our widget, but what if his design is that the #main-content box contains our sidebar widget (or a search box widget, or a social link button widget)? In that case, his .sub-section will again affect our CSS for the widget.
Of course, we can define all the possible CSS styles for our widget, such as
.foobarwidget-sidebar-section .sub-section { color: blue !important;
font-weight: bold !important;
/* ... and all possible CSS styles ... */
}
but that doesn't look like a good feasible solution. We also might use
.foobarwidget-sidebar-section > .sub-section { ... }
so that the .sub-section must be the immediate child, but it doesn't affect a standalone .sub-section affect our widget's CSS. In such situation, what is a good solution to handle it?
Disqus, which needs to handle this sort of thing, opted to solve their problem by putting their widget inside of an iframe where the parent's stylesheet won't affect it. I believe other popular widgety things do this too.
You should use a less generic class for your widget something like .my-custom-widget-name-sub-section
You can put your css file last in the head, with jQuery:
$('head').append('<link rel="stylesheet" href="yourcss-last.css" type="text/css" />');
I would just use an id. The CSS gods frown on IDs, but I think it's perfectly acceptable given the fact that you may or may not have control over the markup / user styles. This will reduce the chances of a user accidentally breaking your layout, while still allowing them to do so if they need it. For better or worse, i've seen this pattern in a lot of jQuery modules that are dealing with similar concerns.
It would also help to have more general "modular" class that describes the general functionality of foobarwidget and is not tied to a location like .sidebar-section. From there, add the styles that make up foobarwidget. This will keep your css cleaner, and allow you to deploy foobarwidget to any area of the page without having to create an entirely new class name.
So, .foobarwidget-sidebar-section .sub-section { border: 1px solid #000 } becomes:
#foobarwidget {
border: 1px solid #000;
background:white;
}
#foobarwidget .subsection {
/* this could probably be declared in #foobarwidget */
color:black; /* one could use !important here, if absolutely necessary */
}
I have this rule in my stylesheet:
input:not([type='button']):not([type='submit']):not([type='checkbox']):not([type='radio']),
select {
padding:8px;
width:224px;
border:1px solid #CCC;
border-radius:5px;
}
This targets all the text fields on my page but I need to prevent it affecting inputs which are inside an element with a certain class. I'm using ckeditor and need to not affect the fields in the dialog boxes that it creates - this means I can't just overwrite the rule afterwards.
I've tried adding :not(.cke_editor_pageContent_dialog input) but that doesn't work for obvious reasons. I can't seem to find an answer to this anywhere
The right approach might be to go with a "whitelist" approach instead of a "blacklist" approach (telling the browser what not to select).
For one thing, it avoids the problem you are experiencing. Also, the :not() selector does not work in IE8 or lower (not sure if that matters). Lastly (just a guess) I have to believe that complex :not statements are more expensive to evaluate.
I would suggest putting either explicit class names on the elements in question, or better yet, wrapping all the non-editor elements inside an element and using that as a style container.
<div class="myStyles">
<!-- elements that should be styled -->
<input type="text" />
</div>
.myStyles input[type="text"]{
padding:8px;
width:224px;
border:1px solid #CCC;
border-radius:5px;
}
I realize that this may require more markup, but it will probably be easier to maintain in the long-term.
Such a long and complicated selector will quickly become unmaintainable in the long run.
It would be much easier and cleaner to add a common class on the elements you want to style the same way.
.text-field {
padding:8px;
width:224px;
border:1px solid #CCC;
border-radius:5px;
}
I know the better answer has already been given, but just for the record, and to augment Tim's answer.
If you want to work with inputs that either have type="text" or don't have a type attribute at all, use this selector:
input:not([type]), input[type='text']
How is it possible to override styles specified in another style sheet?
I do not want to use the !important tag to override them. I would much rather specify a new style sheet, put styles in there. Could this be achieved by changing the load order of the style sheets?
It depends. CSS stands for Cascading Style Sheets, and there's a specific order that styles are applied in, overwriting previous styles. Without going into too much detail:
If your rules have the same specificity, just load your stylesheet second and everything will work fine.
If your rules have higher specificity, the order won't matter.
If your rules have lower specificity, you'll need to modify them to match.
So, what's specificity? Basically, it's the sum of each selector in a rule. So this:
a {
background-color: black;
color: white;
}
Has less specificity than this:
body a {
color: orange;
}
ID selectors have higher specificity than class selectors, which have the same specificity as pseudo-class selectors, which have higher specificity than tag selectors. So if all your content is contained in a <div> with an id of content, you would be able to override a style that looks like this:
body a {
border: 0;
}
With:
#content a {
border: 1px solid black;
}
The boostrap stylesheet should be loaded first, your stylesheet second, this way your overwrites will be picked up.
This is called "cascading", from the documentation:
Cascading
This is the capability provided by some style sheet languages such as CSS to allow style information from several sources to be blended
together. These could be, for instance, corporate style guidelines,
styles common to a group of documents, and styles specific to a single
document. By storing these separately, style sheets can be reused,
simplifying authoring and making more effective use of network
caching. The cascade defines an ordered sequence of style sheets where
rules in later sheets have greater precedence than earlier ones. Not
all style sheet languages support cascading.
If you can increase the specificity of styles, you can do this without the !important.
For example:
HTML
<div id="selector">
<a>Hello</a>
<a class="specific">Hi</a>
</div>
CSS
div a {}
Will be ignored, if you give a specific class inside #selector
.specific { }
Here is a demo explaining my point. Basically, the idea is to define the styles as closely as possible.
look at http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html.
<p class="example">
This is a <strong>test</strong>.
</p>
strong { color: red; }
p strong { color: green; }
p.example strong { color: blue; }
The text will be blue. The order of the rules doesn't matter.
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.