CSS: why is the "div#container" syntax used instead of just #container? - css

I'm seeing this "div#container" syntax being used in CSS and I'm wondering how it works. Anybody has a resource for it?

As well as being a unique reference as mentioned above, IDs increase specificity (I highly recommend you read this article or one similar http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/, understanding specificity in css will make your life easier).
Ill try to explain with a short example - take the following:
div#item { background: blue}
<div id="item" class="item">Hello world</div>
This says make any divs with the ID 'container' blue, but if you then add the following styles after it in your stylesheet
#item {background: purple}
.item {background: green}
the assumption is that the container would be green because stylesheets are cascading and the class with green background comes last. However this isn't the case, an ID has greater precedence and will override a class even if the class comes later. Additionally the item would not be purple because you have added the div before the id earlier on. Having the div and the id increases the specificity further.
People often specify items in css like this: div#container to add extra importance to the style or to specifically state that only DIVS with the id container can be blue.
I would recommend not doing this it becomes harder to override and the style then be comes unusable if you want to make something else have the background blue. So for example the following would not make the paragraph blue because the style specifically states divs.
div#item {background: blue;}
<p id="item">Hello world</p>
If you wanted to override the div#item to be pink instead of blue you might have to do something like the following.
div#item.item {background: pink}
This doesn't seem that bad but when you start building complex websites this can make your css really clunky.
My advice is to make your css as re-usable as possible e.g. the following can be easily overwritten and reused on any tag.
.item { background: blue;}
Hope that helps! Seriously read up on css specificity, it will really help you out.

From the CSS standard itself, a chart of selector syntaxes.
The one you're looking for is near the end:
E#myid Matches any E element with ID equal to "myid".
In other words, that selector will match <div id="container">.
Of course, id values must be unique, so you shouldn't need to specify an element name. You could use *#container or just #container, and many people do. Putting the element name in explicitly might be considered more self-documenting.

http://www.w3schools.com/css/css_selectors.asp
Try to look at this . This will teach you, how this works.
#abc {
text-align: center;
color: blue; }
now anywhere you use #abc text will be aligned center and text color will be blue.
You can also customize it as per your needs.

Related

CSS for td in table using a wildcard

I'm having some trouble with some CSS. I have a number of unique tables with a similar format name, and I need to set the background color on some of them. However, if I try and use a wildcard the style gets overwritten by a parent CSS file.
The background colour here works fine:
#AllProtectedServers1 td.status.online{
color: green;
background-color: yellow;
font-weight: bold;
}
But the background colour doesn't work here as it's being overwritten higher up (although everything else does):
td.status.online {
color: green;
background-color: yellow;
font-weight: bold;
}
I'm going to have 20+ tables all starting with "AllProtectedServers", so naming them all individually is going to make the css huge. Is there anyway I could use a wildcard? I've tried using div[id^='id_'] and similar selectors without any luck.
Anyone have any ideas of what I could use instead?
Update:
Please note the ID's are unique (AllProtectedServersCompany1, AllProtectedServersCompany2, etc), but they all start with AllProtectedServers. I want to create some CSS that will override the stylesheet for the table that is overriding my changes and use a wildcard so I don't have to specify each one.
Maybe this would help:
td.status.online
{
color: green;
background-color: yellow !important;
font-weight: bold;
}
Alpipego's comment is not correct. You're perfectly fine using ID selectors (#) for CSS. These can be overwritten by other ID selectors of the same or higher specificity (depending on page order) or the !important rule.
However, you want to avoid using !important as a CSS rule because that can back you into a corner and become a maintenance nightmare.
As a matter of fact what you need to learn about is CSS Specificity. I recommend reading the CSS: Specificity Wars for an entertaining but educational overview of how CSS Specificity works.
http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
Smashing Magazine also published an article on it that's more extensive:
http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
You do want to be careful about not going crazy with specificity. ID's are (supposed to be) unique per page, so if you end up with a lot of deeply nested rules (#foo .bar .baz .goo), you're probably looking at needing some refactoring.
So, if you use Chrome, pop open the developer tool and look at the CSS selector and determine the specificity. All you need to do is:
a) Match the specificity but make your style come later in the DOM page order
or
b) Use a higher specificity
That's all there really is to it.
I hope that helps!
Cheers.
jmbertucci's answer is quite correct, if perhaps a little incomplete, I will expand with some examlpes.
One of the most overlooked aspects of CSS is specificity rules. As mentioned by jmbertucci please see:
http://csswizardry.com/2014/07/hacks-for-dealing-with-specificity/
http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html
A little more googling will present a wealth of articles for you.
Let's take some base html and css and a bit of a guess as to what you have.
HTML
<table class="myTable">
<tr>
<td class="status online">Online</td>
<td class="status offline">Offline</td>
</tr>
</table>
CSS
table.myTable td.status
{
background-color:#fff;
}
td.status.online
{
background-color:#f00;
}
Fiddle
This will result in a white background for "online" as table.myTable td.status is more specific than td.status.online.
In this example we need to make the second selector more specific. As you mentioned adding an ID results in what you want as IDs have an extremely high specificity score and a very hard to over-write. So much so that some say never to use them*. A simple solution in this example is to add table to the seconde selector.
table td.status.online
{
background-color:#f00;
}
This results in a red background for "online"
Fiddle
Adding table may not work in your instance. YOu need to find the style rule that is being applied using Chrome Developer Tools or Firebug for Firefox and create a rule that is more specific.
If you provide more information I may be able to provide a more specific answer.
* A note on ID's ID's extremely high specificty is both their strenth and weakness. I believe they can be used, but with caution. If you want to style a specific part of a page in a specific manner, you may have a canditate for ID. Think along the lines of a header and footer before the days of HTML5. Another good example may be <section id="discalimer">, using an ID provies two benifits: it's an anchor for specific styling and it can be linked to, e.g: Disclaimer. A further read: http://www.zeldman.com/2012/11/21/in-defense-of-descendant-selectors-and-id-elements/
Keep in mind the arguments on weather to use IDs or not are a matter of optinion and their are good points on both sides. W3C, the standards guys, has no stance on this. If where you work has a coding guide, stick to that mandate. If you're unsure, don't use them in CSS to be safe. Most importantly keep IDs unique.
Andy68man, no wildcard needed, just use a class. Same class for all the tables if they all share the same properties. As in (first the HTML):
<table class="allProtectedServers"> ..... </table>
<table class="allProtectedServers"> ..... </table>
<table class="allProtectedServers secondClass"> ..... </table>
and the CSS:
.AllProtectedServers td.status.online { ... }
If there are one or more properties that only some of the tables have, create another class and give those particular tables both classes, as in the third line of HTML above.
Alternatively, if that still gets overruled by the CSS above, put a single div round all the tables or even the whole page (or there may already be one), give the div an id, and add that into your selector to increase it's specificty (your first bit of code above shows the extra id will be enough to overrule the other CSS that's causing your problem):
#myDiv td.status.online { ... }

a:hover in css stylesheet doesn't show when

when I do this, it works:
.view-current-sales .col-first a {color:#66ff66;}
when I add the hover, it doesn't work anymore
.view-current-sales .col-first a:hover {color:#66ff66;}
any ideas?
I think you are confusing a few things with the a tag and its accompanied hover counterpart. Let's break it down really fast using a different example.
The HTML:
<div class="nohover3">
Test 3
</div>
The CSS:
.nohover3 a {
color:#66ff66;
}
.nohover3 a:hover {
color:blue;
}
Now, I am assuming you are enclosing these a tags in some sort of div or other containing tag to have it's own separate class. Now, this HTML renders one single a tag that is accompanied by two CSS elements. The first CSS element gives the a tag its starting color, meaning it automatically starts with that lime-green color you have provided me in the original question. The second element gives the hover a different color, in this case, the color goes from that lime-green to blue.
With that being said, let's look at your example but with a bit more cleaned up code:
The HTML
<div class="nohover2">
Test 2
</div>
The CSS:
.nohover2 a {
color:#66ff66;
}
.nohover2 a:hover {
color:#66ff66;
}
In this case, both the first and second element are producing the same color for the a tags. That means the color the a tag is to begin with (lime-green) is the same as the color when you hover over the a tag(also lime-green). Which means it stays the same color whether it is hovered or not.
To paint a clearer picture here is a JsFiddle to represent what I have just said:
DEMO
I apologize ahead of time for the poor class names, creating examples is not my strong suit at the moment.
CSS uses a point-scoring system in determining which conflicting styles to use. Elements are worth 1 point, classes are worth 10 points and IDs are worth 100 points.
Try using "Inspect Element" in your chrome browser or similar in other browser types, it will tell you if another style is scoring higher and thus its hover style is used instead.
If thats the case try replacing the class reference for a:hover to an id reference to obtain a higher score for the a:hover you wish to use.
A nice description can be found here Points in CSS specificity
If all else fails try tagging your hover style with "!important" to ensure the stype is used.

Is there a way to apply a CSS class from within a style?

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.

Order of prioritization when using multiple contradictory css files

When using multiple css files on the same page and they collide, how do i know which one is going to be used? For example, if one says blue body background and the other one says red.
Quick Answer:
If both pieces of CSS have the same specificity (for example, they're both body{), then whichever gets called LAST will override the previous one.
BUT, if something has higher specificity (a more specific selector), it will be used regardless of the order.
Example 1:
<div class="container">
<div class="name">Dave</div>
</div>
<style>
.name { color: blue; }
.name { color: red; }
</style>
The above example will make the color red. Both selectors are the same, and therefore also have the same specificity. And because CSS reads top-to-bottom, we first tell it to be blue, but then we override that by telling it "nevermind, make it red".
Example 2:
<div class="container">
<div class="name">Dave</div>
</div>
<style>
#container .name { background-color: blue; }
.name { background-color: red; }
</style>
The above example will make the background color blue, even though blue was first because the selector is more "specific".
Exception (the use of !important):
The inclusion of !important will override both specificity and order, but in my opinion, should only be used if you're trying to mess with a third party code in which you don't have access to change it any other way.
External CSS:
Overwrite rules work the same on external CSS files. Just imagine putting them first-to-last, top-to-bottom. The selectors called in the first file(s) will get overwritten by same-specificity-selectors in any subsequent files. But specificity will still trump order within the same file or in multiple files.
How to test:
In Chrome, Firefox, and modern versions of IE (probably Safari too), you can right click on something and click "Inspect Element". This will show you the HTML as well as any applied CSS. As you scroll down the CSS (usually on the right), you'll see things that are crossed out - that means they're either incorrect CSS or have been overwritten. To test, you can modify the CSS selectors (either in your own code or right there in the developer tools box) to make them more specific and see if that makes then un-crossed out...etc. Play around w/ that tool - it's VERY helpful.
Not sure how "specific" something is?
Try some of the many online CSS specificity tools:
https://polypane.app/css-specificity-calculator
https://specificity.keegan.st/
https://www.codecaptain.io/tools/css-specificity-calculator

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