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']
Related
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 :-)
I'm trying to be more modular in my CSS style sheets and was wondering if there is some feature like an include or apply that allows the author to apply a set of styles dynamically.
Since I am having a hard time wording the question, perhaps an example will make more sense.
Let's say, for example, I have the following CSS:
.red {color:#e00b0b}
#footer a {font-size:0.8em}
h2 {font-size:1.4em; font-weight:bold;}
In my page, let's say that I want both the footer links and h2 elements to use the special red color (there may be other locations I would like to use it as well). Ideally, I would like to do something like the following:
.red {color:#e00b0b}
#footer a {font-size:0.8em; apply-class:".red";}
h2 {font-size:1.4em; font-weight:bold; apply-class:".red";}
To me, this feels "modular" in a way because I can make modifications to the .red class without having to worry so much about where it is used, and other locations can use the styles in that class without worrying about, specifically, what they are.
I understand that I have the following options and have included why, in my fairly inexperienced opinion, they are less-than-perfect:
Add the color property to every element I want to be that color. Not ideal because, if I change the color, I have to update every rule to match the new color.
Add the red class to every element I want to be red. Not ideal because it means that my HTML is dictating presentation.
Create an additional rule that selects every element I want to be red and apply the color property to that. Not ideal because it is harder to find all of the rules that style a specific element, making maintenance more of a challenge
Maybe I'm just being an ass and the following options are the only options and I should stick with them. I'm wondering, however, if the "ideal" (well, my ideal) method exists and, if so, what is the proper syntax?
If it doesn't exist, option 3 above seems like my best bet. However, I would like to get confirmation.
First of all you cannot do apply-class:".red";
to perform this type of action i will suggest you to use this method
.red {color:#e00b0b;}
h2 {font-size:1.4em; font-weight:bold;}
.mymargin{margin:5px;}
<h2 class="red mymargin">This is h2</h2>
and to use in div
<div id="div1" class="red mymargin"></div>
In this case if you will change in .red class.it will be changed everywhere
Short answer: There's no way to do this in pure CSS.
Longer answer: Sass solves this problem via the #extend directive.
.error {
border: 1px #f00;
background-color: #fdd;
}
.seriousError {
#extend .error;
border-width: 3px;
}
This lets you keep your CSS modular in development, though it does require a precompilation step before you use it. It works very nicely though.
You can use the DOM in javascript to edit the id and/or class attributes of HTML tags dynamically.
I agree with DarthCaesar and jhonraymos. To update a class using JavaScript, all you would need is a simple:
function toggleColorClass(e){
var redClass = document.getElementsByClassName('red');
redClass.removeAttribute('class', 'red');
/*Set the class to some other color class*/
redClass.setAttribute('class', 'blue');
}
Of course, to make this work, you would need to include the above function in your document somewhere... if this is all the JS you're using you can probably stick it in the head or even use it inline. You would probably also want to write it so that the toggle goes in both directions, i.e. turning red on and off. Furthermore, jhonray's snippet is probably how you would want to mark up your CSS.
I've been relying on the following technique for a while. But I've not come across it often, and I wasn't able to find information on it. Perhaps it has a proper name that I am not aware of? I call it chaining because it seems to be exactly that: chaining CSS class names together. But doing a search on chaining yields info on jQuery for the most part.
.button {
background-color:#ccc;
}
/* This is what I'm unsure of, notice there is no space between .button and .on */
/* If there were, .on apply to the child of .button, but that's not my intention */
.button.on {
background-color:#fff;
}
It allows me to use a single class name (on) to differentiate between the states of multiple elements.
<a class="button"></a>
<a class="button on"></a>
<a class="button-two"></a>
<a class="button-two on"></a>
<!-- etc... -->
It's very handy with dynamic pages when you need to toggle an on class on several elements using a single class name.
But is it valid?
This is perfectly valid CSS....
Although IE6/and IE7 do have some issues with class-chaining.
Yes, it is valid CSS, although it doesn't work quite right in IE6 - it will only apply the last class, rather than all of them. You can read more over at CSS-Tricks.com on the topic.
This is perfectly valid and very common.
You can see it in this very page:
a.comment-user.owner {
padding: 2px 5px;
}
However, IE6 will ignore all but the last class.
In IE6, .a.b is equivalent to .b.
In CSS2 and even in the upcoming CSS3, I can't find something that would be completely natural and time-saving - applying CSS styles from within other styles, rather than from HTML.
For example:
.awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
.alwesome-image; // or something like that - this is similar to a function call in a functional language
padding: 2px;
}
Oftentimes, one doesn't have access to generated HTML, so modifying CSS is the only choice.
This sort of inheritance support would make life a lot easier because we'd be able to treat CSS rules as "functions" and reuse the code rather than duplicate it.
Or am I missing something and CSS does support this (I've never seen it before?) or plans on supporting it? Enlighten me please.
Edit: Consider another example which shows that declaring .awesome-image, .super-awesome-image {common rules} is not elegant:
.border5 {
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px
}
I would much rather not pile up every other class that would want to have a border radius in the same definition. Alas, that's what needs to be done without functional support (I mentioned a lot of times there's only access to the CSS file and not the HTML itself).
In CSS, this is achieved as follows:
.super-awesome-image, .awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
padding: 2px;
}
Styles can be applied to multiple classes at once, which allows for easy inheritance.
There has been much debate as to whether CSS should be given functional programming techniques or layer inheritance, but this style of class inheritance will probably remain.
EDIT:
If you can generate styles with php, such inheritance should be quite doable.
Check out these scripts (which mostly deal with CSS variables, but may do more):
http://www.shauninman.com/archive/2005/08/05/css_variables
http://www.joesapt.net/2005/09/03/08.46.34
http://interfacelab.com/variables-in-css-via-php/
http://www.conditional-css.com/
It would make recursion possible (which would mean parsers would need to be able to recover from it)
Multiple rule-sets can use the same selector, so which one would apply? Or would all of them?
You can achieve what you want with:
<img … class="awesome-image super-awesome-image">
or
.awesome-image,
.super-awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
padding: 2px;
}
It kind of does support what you're suggesting, via the Cascade and inheritance. These are essential parts of CSS to understand, but they're sometimes a bit, er, idiosyncratic ...
I think the problem you mention is valid, but in those situations where the web programmer is completely separate from the web designer, it puts the onus on the initial project management to ensure both do what they're meant to. It's obviously a good philosophy to separate function and style, but there will always have to be some kind of link between the 2 and that is carried out by specifying the external CSS file(s). That's the reason it's important to define Id's and Class's carefully and always factor in some scope for change, i.e never make your CSS too general and always define ID's and Class's in the HTML for elements even when you're not styling them right now. It's a fine line to walk though between being pedantic and being careful, but then trying to think 6months/1year/5years ahead always would be ;)
This has always been my own personal approach.
I think "mixins" in LESS or SASS do exactly that.
As for why CSS itself doesn't do that, I don't know. First, I'd like to know why CSS doesn't give me a sane way to vertical align my content, or to shrink-fit a container (with floats), or to override overflow:hidden clipping for selected elements, or to do absolute positioning in relation to opposite edges, or ... and a lot of other things.
Your idea sounds nice, though.
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.