In CSS what is is the difference between element#id-name and #id-name for the same element.Since id's are unique, then why are there the two forms given before used. For eg: Difference between div#para and #para.
element#id-name is "stronger" than #id-name and if there are multiple reference to one element, the stronger is the one applied to the element
see fiddle http://jsfiddle.net/kJrCT/
div#para only applies to divs with id "para", while #para applies to all element types with that id. Consider the fact that on another page you could have a span with id "para". You could use div#para to style only the div, span#para to style only the span, and #para to apply css styling to all #para elements throughout the website.
There are a number of reasons you might like to use the same id for different elements depending on the page being viewed. Also, being more or less specific affects the priority of the style being applied.
You can use the same css on multiple pages and if you use the same id-name but with different element you can use some common rules.
Example:
#title{
color: red;
}
h2#title{
font-size: 16pt;
}
h1#title{
font-size: 22pt;
}
So, your h1 with title id-name will be red and with size 22pt and your h2 with id-name (on other page) will be red too but with 16pt size.
In your case, Both are exactly the same. They refer to the same element.
Its just for readabilty, so that the person looking # the css can know which element has the id "para".
But Generally this is useful when you apply the same[generic] class to many elements at the same time, and you want to refer to only one specific element, having that class.
Eg:
.pull-left{
float:left;
}
// This applies to all the elements with this class
This can be given to a 'p' or a 'div' or any element. but if you want to refer to a div with the class pull-left, then you can use
div.pull-left /// refers only to the <div>'s having class pull-left
Related
Suppose the following HTML:
<li>
Link
</li>
Which one of the CSS styles is correct to set the font-size?
li {
font-size: 12px;
}
li a {
font-size: 12px;
}
Many CSS styles are inherited from a parent to its children, font-size included.
If you imagine this hierarchy as a tree, the general rule is to apply styles as high (parent) as possible but as low (children) as necessary. Styles should also be as general as possible (meaning low selector count).
In your case this means that if you only want to select the ‘a’s inside ‘li’s you should use the second rule. If you want the font-size of all ‘li’s to be 12px you may apply the style to the li or ul, ol or even the body or an outer container.
For your simplified example, either one will work. The first would affect all list items, though, whereas the second would only affect links within list items. Which one is appropriate depends on whether/how you're using list items elsewhere in the code.
I have a style sheet that consists styles that affects two elements in my page, I can't change the classes for my elements, is there any way to make sure that the styles apply to only one specific element in my page not for the other.
Have you tried the first-of-type selector?
ex.
p:first-of-type {
background:#ff0000;
}
Yes. You can do that by specificity.
Select topmost parents and go on targeting their childs until you reach the last child element that you need to apply styles for.
If you can add an id to it or if any id is dynamically generated, just create a specificity for the same and you will get your thing done.
For Instance,
body div#your id name div.your_class1 > div.your_class_element_that_you_want_to_style{/* your values */}
Hope this helps.
PS: In the illustration, div is used as a reference and you can select the elements accordingly to your HTML structure.
If there are two, you use the :first-of-type selector:
div.selector:first-of-type {
/* styles here */
}
There are already many questions related to this. But I'm still not clear. Also not sure if the title of the question is correct. Here's my problem:
What the below CSS code means?
#nav li { /*some cssA*/ }
#nav li.over { /*some cssB*/ }
#nav li a { /*some cssC*/ }
#nav li a:hover { /*some cssD*/ }
#nav li ul a span { /*some cssE*/ }
As per my understanding, please correct me if I am wrong:
Line 1: every li element within any element with id="nav" will have styling cssA
Line 2: When I put my cursor over every li element within any element with id="nav" will have styling cssB
Line 3: every a element within every li element within any element with id="nav" will have styling cssC
Line 4: When I hover every a element within every li element within any element with id="nav" will have styling cssD
Line 5: Every span element within every a element within every ul element within every li element within any element with id="nav" will have styling cssE. Also anyother ul or a element will not have this style untill unless the parent element has id="nav"
You are correct on all except .over, The "." represents a class. and "#" represents ID. But yeah, you've got the concept down.
Also, if you want to "Override" as the title says, you'll add
!important
to the end of any rules you want to take precedence over the others.
you can override the css by giving !important or you can give inline style.
priority of inline css is high then external css
All of the existing answers are correct, but there is a bit more to it than has been given already.
As has already been said, "li.over" is a combined selector - it will selector li elements that also have a class of "over". If you wanted to use different CSS properties or property values whilst the mouse is over (hovering over) the element then you use the pseudo class selector "li:hover". These are called pseudo class as you aren't selecting something that is part of the document, but based on the state of an element. There are also pseudo elements which again aren't in the document directly, but logical extensions of the document structure - for example first-child, first-of-type, fifth-of-type, odd items etc.
"#nav li ul a span" is a descendant selector, as you say it will select elements that are children (at any level) of each parent, so "#nav li" selects "li" elements contained within an item with ID "nav" - even several levels down.
If you want to select items that are direct children of the parent then you can use the ">" symbol. I.e. "#nav > li" will select li elements that are directly below any item with an ID of "nav", but not any li elements that are children of that element, or indeed elements below that.
Incidentally "#nav" is exactly equivalent to "*#nav" as it selects any element with the ID, you could also write "ul#nav" if you only wanted to select ul elements with the ID. This could in turn be combined with a class "ul#nav.bar" or even multiple classes "ul#nav.bar.touch".
Removing the space between the selectors like this combines them, so in the last case instead of looking for an item with class "touch" inside an item with class "bar" inside an item with ID "nav" inside a "ul" element, you are selecting a "ul" element with an ID of "nav" and both the classes "bar" and touch". An element like this-
<ul class="bar touch" id="nav">...</ul>
It is also possible to use attribute selectors, so if you wanted to select links which will open in a new window you could use "a[target=_blank]" - which selects based both on the presence of the attribute and the value - or if you wanted to select links with any href value you could use "a[href]". This simply selects all elements with this attribute.
On top of that you can even select items which are adjacent (next to) another element, if you wanted to select all paragraphs directly following an image then you would use "img + p" in your selector, or "p + img" if you wanted to select images directly following a paragraph. As always the last item in the selector is the one the styles are applied to.
It is generally considered good practice not to be overly specific with CSS selectors, as it makes your code much less re-usable. Unless you need to write "div.widget" just write ".widget" as the otherwise you'd not be able to create a "widget" using other elements, and it makes it much harder to override these properties later on in those cases you might need to.
To wrap up selectors, there's a good introduction to CSS selectors on MDN and Code School (paid course provider) also have a excellent online foundation course on CSS available for a very reasonable price which will go through selectors in some detail.
With regard to overriding classes, there are two further concepts you should understand - cascade order and specificity.
Given a HTML snippet of-
<div class="widget">
<p>
Some text you want to style
</p>
</div>
And the following CSS-
#widget p { color: yellow; }
p { color: blue; }
The color of the text would be yellow and not blue because the specificity of the first selector is greater (more specific) than the second. To understand this I suggest you have a play with a Specificity calculator and have a read of the Smashing Magazine tutorial on the subject.
In short though, inline styles trump all, and the more specific a selector the more likely it is to be applied in place of other selectors that would otherwise apply different property values. The value in the selector with the highest specificity score "wins", but other property values from selectors with lower specificity that do not clash will also still be applied to the element.
For example, altering our earlier CSS-
#widget p { color: yellow; }
p {
color: blue;
font-weight: bold;
}
The text will still be yellow, but will also be bold as there is no font-weight property given in the selector with higher specificity.
The last concept you should understand is what happens when two or more rules have identical specificity.
#widget p { color: yellow; }
#widget p {
color: blue;
font-weight: bold;
}
In this case our text is now blue as the second rule appears later in the stylesheet and thus overrides the first. If you have multiple stylesheets then the rules from the last stylesheet to appear in the document head will override rules with identical specificity.
In almost all cases you should use a more specific or the order of the selectors within the stylesheet in order to apply the right styles to the right element, and absolutely should not be routinely using the !important flag to achieve this unless absolutely necessary. See http://james.padolsey.com/usability/dont-use-important/ for a fuller explanation than I give here, but it rapidly becomes unmaintainable (what do you do when everything is "important") and it is also not accessible for users who may wish to override your styles in their user agent stylesheet (local to their browser) in order to help them read or use the page (increasing font size, contrast with background colour etc.)
Here is the page I am affecting:
http://www.careerchoiceswithlaura.com/blog/
Inspecting the elements will show that I set up one class "blog-post" and added it to each entry on the page. Then, I use a simple algorithm to apply a class named "even-numbered" or "odd-numbered" as well for appropriate entries so I can stagger the color effects and make the page more readable.
The problem is, that when I apply rules using the following line in my CSS file:
.blog-post .odd-numbered { background: #ddd; }
..it doesn't affect the elements with both blog-post and odd-numbered; in fact, the rule affects nothing on the page.
Could someone explain why, and which class selectors I should be using to affect said elements?
I researched online, and find this article at W3 very helpful usually (and it appears that the rule should be working if you look at /blog/:279 on the page I mentioned above), but even with the rule there it doesn't seem to be anything to the elements I am trying to target.
Your example selector targets elements with the class odd-numbered that have an ancestor element with the class blog-post.
In your HTML, the .blog-post element is also the .odd-numbered element.
Your selector, then, should be .blog-post.odd-numbered (note the lack of a space).
You'll want these CSS pseudo-selectors:
elementname:nth-child(even)
and
elementname:nth-child(odd)
Documentation:
http://www.w3.org/Style/Examples/007/evenodd
To style the same element with two classnames, you will want (without a space):
.blog-post.odd-numbered { background: #ddd; }
You original style, with a space, styles an element with the class odd-numbered inside an element with the class blog-post
from CSS3
:nth-child(odd)
You should apply as .blog-post.odd-numbered { background: #ddd; } without space btw css classes, If it is applied to same element.
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.