Is there any difference between this
#id {
}
and this
div#id {
}
Yes. There is mainly two differences:
The first selector matches any element with id="id", while the second only matches div elements with that id.
The second selector is more specific, so if you have both and they match the same element, the styles from the second will have precedence.
Normally you would use the first selector. As the id should be unique in the page it would only target a single element.
The second selector would be useful if you use the same style sheet for several pages, and you either want to target the id under certain conditions, or if you want to override another rule by making it more specific.
The selectors behave differently:
#id is same as writing *#id (the asterisk selector is implied if tag name is omitted).
It matches any element that has an id of id.
div#id matches an element that is a div and has an id of id.
It is more specific than the above example.
In general, using #id selector is sufficient since ids are (supposed to be) unique inside a page. However, there are certain situations where you could use div#id.
Example 1
You use different elements for similar purpose therefore you want to assign them same id but style them differently, then you must be more specific:
<!-- page 1 -->
<ul id="features" title="All amenities">
<li>Spa</li>
<li>Pool</li>
</ul>
<!-- page 2 -->
<ol id="features" title="Top 3 amenities">
<li>Spa</li>
<li>Pool</li>
</ol>
Example 2
You can add a tag name to add weight to your selector. Consider this example:
<div id="header">
<img>
<div id="logo"><img></div>
<img>
</div>
/* file 1 */
#logo img { border: thin solid; }
/* file 2 */
#header img { border: 0; }
The first rule adds a thin border to images inside logo, the other rule removes border from all images inside header (including the one inside logo). In order to force the thin border rule you can change it to div#logo img so that it becomes more specific than the other rule.
Short answer: Yes.
#id {} targets a single ID selector wherever applied in a single HTML document. For example, <span id="id">...</span>, or <p id="id">...</p>
div#id {} will look for a <div> element that has an ID of #id, for example: <div id="id"></div> and cannot be used on any other tag except a <div>.
Note that ID selectors should only be used once semantically in a HTML document.
On a larger scale and more constructed case to this question, you should look at CSS Specificity; a well written and best-practise approach to specificity in CSS.
Also, take a look a CSSGuidelin.es, another well-written document on dealing with CSS selectors and their differences.
#elementid selector will select all elements having the id "elementid"
On the other hand, div#elementid selector will select only divs having id "elementid"
Related
I'm trying to figure out why one of my css classes seems to override the other (and not the other way around)
Here I have two css classes
.smallbox {
background-color: white;
height: 75px;
width: 150px;
font-size:20px;
box-shadow: 0 0 10px #ccc;
font-family: inherit;
}
.smallbox-paysummary {
#extend .smallbox;
font-size:10px;
}
and in my view I call
<pre class = "span12 pre-scrollable smallbox-paysummary smallbox ">
The font (The overlapping element) shows up as 10px instead of 20 - could someone explain why this is the case?
There are several rules ( applied in this order ) :
inline css ( html style attribute ) overrides css rules in style tag and css file
a more specific selector takes precedence over a less specific one
rules that appear later in the code override earlier rules if both have the same specificity.
A css rule with !important always takes precedence.
In your case its rule 3 that applies.
Specificity for single selectors from highest to lowest:
ids (example: #main selects <div id="main">)
classes (ex.: .myclass), attribute selectors (ex.: [href=^https:]) and pseudo-classes (ex.: :hover)
elements (ex.: div) and pseudo-elements (ex.: ::before)
To compare the specificity of two combined selectors, compare the number of occurences of single selectors of each of the specificity groups above.
Example: compare #nav ul li a:hover to #nav ul li.active a::after
count the number of id selectors: there is one for each (#nav)
count the number of class selectors: there is one for each (:hover and .active)
count the number of element selectors: there are 3 (ul li a) for the first and 4 for the second (ul li a ::after), thus the second combined selector is more specific.
A good article about css selector specificity.
Here's a compilation of CSS styling order in a diagram, on which CSS rules has higher priority and take precedence over the rest:
Disclaimer: My team and I worked this piece out together with a blog post (https://vecta.io/blog/definitive-guide-to-css-styling-order) which I think will come in handy to all front-end developers.
What we are looking at here is called specificity as stated by Mozilla:
Specificity is the means by which browsers decide which CSS property
values are the most relevant to an element and, therefore, will be
applied. Specificity is based on the matching rules which are composed
of different sorts of CSS selectors.
Specificity is a weight that is applied to a given CSS declaration,
determined by the number of each selector type in the matching
selector. When multiple declarations have equal specificity, the last
declaration found in the CSS is applied to the element. Specificity
only applies when the same element is targeted by multiple
declarations. As per CSS rules, directly targeted elements will always
take precedence over rules which an element inherits from its
ancestor.
I like the 0-0-0 explanation at https://specifishity.com:
Quite descriptive the picture of the !important directive! But sometimes it's the only way to override the inline style attribute. So it's a best practice trying to avoid both.
The order in which the classes appear in the html element does not matter, what counts is the order in which the blocks appear in the style sheet.
In your case .smallbox-paysummary is defined after .smallbox hence the 10px precedence.
First of all, based on your #extend directive, it seems you're not using pure CSS, but a preprocessor such as SASS os Stylus.
Now, when we talk about "order of precedence" in CSS, there is a general rule involved: whatever rules set after other rules (in a top-down fashion) are applied. In your case, just by specifying .smallbox after .smallbox-paysummary you would be able to change the precedence of your rules.
However, if you wanna go a bit further, I suggest this reading: CSS cascade W3C specification. You will find that the precedence of a rule is based on:
The current media type;
Importance;
Origin;
Specificity of the selector, and finally our well-known rule:
Which one is latter specified.
Also important to note is that when you have two styles on an HTML element with equal precedence, the browser will give precedence to the styles that were written to the DOM last ... so if in the DOM:
<html>
<head>
<style>.container-ext { width: 100%; }</style>
<style>.container { width: 50px; }</style>
</head>
<body>
<div class="container container-ext">Hello World</div>
</body>
...the width of the div will be 50px
AS is state in W3:
W3 Cascade CSS
the orden that different style sheet are applied is the following (quote from W3 cascading section):
user agent declarations
user normal declarations
author normal declarations
author important declarations
user important declarations
More information about this in the referred W3 document
Element, Pseudo Element: d = 1 – (0,0,0,1)
Class, Pseudo class, Attribute: c = 1 – (0,0,1,0)
Id: b = 1 – (0,1,0,0)
Inline Style: a = 1 – (1,0,0,0)
Inline css ( html style attribute ) overrides css rules in style tag and css file
A more specific selector takes precedence over a less specific one.
Rules that appear later in the code override earlier rules if both have the same specificity.
In a simple and short way, one should keep in mind the two things below:
Inline CSS has a higher priority than embedded and external CSS.
So final Order is: Value defined as Important > Inline > id nesting > id > class nesting > class > tag nesting > tag
There is one <p> tag with class .eleclass and id #eleid and i have specified 3 css to the <p> tag one specified with class second with id and third with just p declared.
p#eleid{
color:yellow;
}
p.eleclass{
color:blue;
}
p{
color:red;
}
<p id="eleid" class="eleclass">
hello para.
</p>
Now i wonder why the rule applied to p#eleid is working when css runs from top to bottom nature and at bottom color red is specified so <p> should be red in color.
Is there any css rules hidden behind it??
This problem inclues use of id not only class.
It comes down to CSS specificity.
From MDN:
Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied.
As it happens, an ID based selector has higher priority than a tag based selector. This is because an ID is more specific than a tag. In other words, the tag selector applies to all p elements, while the ID will only apply to the p with the ID.
There are ways around specificity, such as the !important keyword - however, I mostly recommend against working around specificity, as it can lead to bugs.
I read an article with some css file
#mainNav #toTop a {
float: right;
margin: 0 8px 0 0;
font-size: 40px;
}
Can someone explain why they have two # things in one css id type ? and how can I use it?
Thank you in advance
I don't know what you mean by a "CSS id type". So I'm just going to explain CSS in general, and we'll see if what this snippet is doing becomes clear.
In CSS you have selectors and property blocks. Your question is about a selector:
#mainNav #toTop a
Selectors are used to target (and on some other platforms to query) HTML (and sometimes XML) elements. This particular rule is using three simple selectors - two id selectors and a tag name selector - put together with two descendant combinators.
That means the selector will target (and the rule block accompanying it will affect) any anchor element (<a>) which is the descendant of any element with id=toTop which in turn is the descendant of any element with id=mainNav.
Since id elements are supposed to be unique, it might seem silly to have two of them in one selector. You can do it if you want to though, and sometimes you'll need to: we haven't spoken about selector specificity.
Specificity defines which rules take precedence over other rules. For example, if two elements both seem to target the same element:
form .label { color: blue; }
#contact-us .label { color: green; }
/* what color is the label? */
... then which rule takes precedence? To figure that out we calculate the specificity. I won't explain the math.
So, let's suppose you have a CSS stylesheet in your project which you can't change - it comes from a 3rd party vendor or something, and it looks like this:
#toTop a { /*...*/ }
If you needed to change the styling of the elements affected by that rule, what would you do?
You could (and probably would) define a new rule with greater specificity. One of the ways you can do that is by adding another id selector to your rule:
#mainNav #toTop a { /*...*/ }
But realistically you could just as easily add any other selector:
div#toTop a { /*...*/ }
Realistically whether it's necessary or not depends on what you're trying to do, what other rules it's interacting with, and what kind of HTML you're dealing with.
Here's another thing to consider: CSS stylesheets are meant to be re-used. What if that element should behave differently if it is in a different place in the document? What if the id="toTop" is sometimes inside the id="mainNav" element on some pages, and in a different place (let's say in the id="footer" element) on others? What if it moves, depending on client-side JavaScript? Then you might want to define CSS like this:
#mainNav #toTop a { /*...*/ }
#footer #toTop a { /*...*/ }
... so ultimately again, why a developer would choose to do this really depends on the CSS, JavaScript and HTML they are working with. It's definitely unusual, but it's not unnecessary nor bad practice.
ID must always be unique. However it is valid to use more than one id to make styles more specific.
In your example you are looking for an element with id #toTop inside #mainNav.
This is a perfectly valid CSS rule. It is very specific. The motivation for this use may have to do with how the page layout is designed and/or how JavaScript handlers interact with the DOM.
This is an example of poor CSS. The selector hierarchy in your example is redundant and unnecessary. It says select all a elements that are descendants of the element with the ID of toTop that is a descendant of the element with the ID of mainNav. So it assumes a basic structure like this:
<div id="mainNav">
<div id="toTop">
link
</div>
</div>
However, as IDs must be unique, only this is needed to target the same elements:
#toTop a
#mainNav #toTop a is using the Descendant Combinator to specify an element a descendant of an element with id toTop descendant of an element with id mainNav.
As said by other answers, this rule seems to be overly specific, because IDs must be uniques and then #toTop a should do the trick.
The real reason behind the choice of declaring this rule is:
Assuming that in a website you have one or more shared CSS (read:
you don't have an different CSS for every page), this rule means:
in a page where a is descendant of #toTop, but #toTop is descendant of an #mainNav element too, then apply this rule;
in a page where a is descendant of #toTop, but #toTop is NOT descendant of an #mainNav element, then DO NOT apply this rule;
because #toTop could be an reusable element that could be declared in different places (one-per-page, of course), for example inside the #mainNav in a page, and inside the #sideNav in another page, with a desired potentially different behavior and look-and-feel.
This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 5 years ago.
#main {
background: #000;
border: 1px solid #AAAAAA;
padding: 10px;
color: #fff;
width: 100px;
}
<div id="main">
Welcome
</div>
Here I gave an id to the div element and it's applying the relevant CSS for it.
OR
.main {
background: #000;
border: 1px solid #AAAAAA;
padding: 10px;
color: #fff;
width: 100px;
}
<div class="main">
Welcome
</div>
Now here I gave a class to the div and it's also doing the same job for me.
Then what is the exact difference between Id and class and when should I use id and when should I use class.? I am a newbie in CSS and Web-design and a little bit confused while dealing with this.
Use a class when you want to consistently style multiple elements throughout the page/site. Classes are useful when you have, or possibly will have in the future, more than one element that shares the same style. An example may be a div of "comments" or a certain list style to use for related links.
Additionally, a given element can have more than one class associated with it, while an element can only have one id. For example, you can give a div two classes whose styles will both take effect.
Furthermore, note that classes are often used to define behavioral styles in addition to visual ones. For example, the jQuery form validator plugin heavily uses classes to define the validation behavior of elements (e.g. required or not, or defining the type of input format)
Examples of class names are: tag, comment, toolbar-button, warning-message, or email.
Use the ID when you have a single element on the page that will take the style. Remember that IDs must be unique. In your case this may be the correct option, as there presumably will only be one "main" div on the page.
Examples of ids are: main-content, header, footer, or left-sidebar.
A good way to remember this is a class is a type of item and the id is the unique name of an item on the page.
ids are unique
Each element can have only one id
Each page can have only one element with that id
classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Javascript cares
JavaScript people are already probably more in tune with the differences between classes and ids. JavaScript depends on there being only one page element with any particular id, or else the commonly used getElementById function couldn't be depended on.
For more info on this click here.
Example
<div id="header_id" class="header_class">Text</div>
#header_id {font-color:#fff}
.header_class {font-color:#000}
(Note that CSS uses the prefix # for IDs and . for Classes.)
However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5.
In CSS there is no "font-color", the style is color so the above should read:
Example
<div id="header_id" class="header_class">Text</div>
#header_id {color:#fff}
.header_class {color:#000}
The text would be white.
IDs must be unique--you can't have more than one element with the same ID in an html document. Classes can be used for multiple elements. In this case, you would want to use an ID for "main" because it's (presumably) unique--it's the "main" div that serves as a container for your other content and there will only be one.
If you have a bunch of menu buttons or some other element for which you want the styling repeated, you would assign them all to the same class and then style that class.
As pretty much everyone else has said use ID for one-off elements and class for multiple use elements.
Here is a quick, over simplified example, take HTML and HEAD tags as read
<body>
<div id="leftCol">
You will only have one left column
</div>
<div id="mainContent">
Only one main content container, but.....
<p class="prettyPara">You might want more than one pretty paragraph</p>
<p>This one is boring and unstyled</p>
<p class="prettyPara">See I told you, you might need another!</p>
</div>
<div id="footer">
Not very HTML5 but you'll likely only have one of these too.
</div>
</body>
Also, as mentioned in other answers ID are well exposed to javascript, classes less so. However modern javascript frameworks like jQuery leverage class for javascript too
ID's have the functionality to work as links to particular sections within a webpage.
a keyword after # tag will take you to a particular section of the webpage.
e.g "http://exampleurl.com#chapter5" in the address bar will take you there when you have a "section5" id wrapped around the chapter 5 section of the page.
The class attribute can be used with multiple HTML elements/tags and all will take the effect. Where as the id is meant for a single element/tag and is considered unique.
Moreoever the id has a higher specificity value than the class.
id:
It will identify the unique element of your entire page. No other element should be declared with the same id.
The id selector is used to specify a style for a single, unique element.
The id selector uses the id attribute of the HTML element, and is defined with a "#".
class:
The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
If there is something to add to the previous good answers, it is to explain why ids must be unique per page. This is important to understand for a beginner because applying the same id to multiple elements within the same page will not trigger any error and rather has the same effects as a class.
So from an HTML/CSS perspective, the uniqueness of id per page does not make a sens. But from the JavaScript perspective, it is important to have one id per element per page because getElementById() identifies, as its name suggests, elements by their ids.
So even if you are a pure HTML/CSS developer, you must respect the uniqueness aspect of ids per page for two good reasons:
Clarity: whenever you see an id you are sure it does not exist elsewhere within the same page
Scalability: Even if you are developing only in HTML/CSS, you need to take in consideration the day where you or an other developer will move on to maintain and add functionality to your website in JavaScript.
You can assign a class to many elements. You can also assign more than one class to an element, eg.
<button class="btn span4" ..>
in Bootstrap. You can assign the id only to one.
So if you want to make many elements look the same, eg. list items, you choose class. If you want to trigger certain actions on an element using JavaScript you will probably use id.
A class can be used several times, while an ID can only be used once, so you should use classes for items that you know you're going to use a lot. An example would be if you wanted to give all the paragraphs on your webpage the same styling, you would use classes.
Standards specify that any given ID name can only be referenced once within a page or document. Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.
This is very simple to understand :-
id is used when we have to apply CSS property to one attribute only.
class is used when we have to use CSS property in many locations within the same page or different.
General :- for unique structure like staring div and buttons layout we use id .
for same CSS throughout the page or project we use class
id is light and class is little heavy
A simple way to look at it is that an id is unique to only one element.
A class is not unique and applied to multiple elements.
For example:
<p class = "content">This is some random <strong id="veryImportant"> stuff!</strong></p>
Content is a class since it'll probably apply to some other tags aswell where as "veryImportant" is only being used once and never again.
Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
A simple way to look at it is that an id is unique to only one element. class is better to use as it will help you to execute what ever you want.
id selector can be used to more elements. here is the example:
css:
#t_color{
color: red;
}
#f_style{
font-family: arial;
font-size: 20px;
}
html:
<p id="t_color"> test only </p>
<div id="t_color">the box text</div>
I tested on internet explorer (ver. 11.0) and Chrome (ver.47.0). it works on both of them.
The "unique" only means one element can not have more than one id attributes like class selector. Neither
<p id="t_color f_style">...</p>
nor
<p id="t_color" id="f_style">...</p>
'#' is the the ID selector, a fundamental part of the CSS language. It matches the HTML element with the given id. I know it but what is the main differences between using .classname {...} or #idselector in a .css file.
.hello { color:000000;}
or
#hello { color:000000;}
The first matches any element with the CSS class hello, the second matchs any element with the id value of hello. For example:
<div class="hello"></div>
<div id="hello"></div>
Precedence. IDs have a higher precedence then class selectors. If you had the following CSS:
.hello { color:#000000;}
#hello { color:#ff0000;}
Assuming the same element had the ID of 'hello' and class of 'hello' the font color of that element would be red since the ID has a higher precedence then the class selector.
Also, you can only have one element with the ID of 'hello' on a page. But you can have an unlimited number of elements with the class of 'hello'.
ID (#hello) should be used for unique, single elements only (for example: login button).
Class (.hello) should be used for elements that can be repeated (for example: navigation menu buttons).
IDs are unique, in a way that a certain element may only have one ID, and only one of the same ID may exist on a page. So the following is invalid:
<div id="first_id second_id"></div>
<div id="third_id"></div>
<div id="third_id"></div>
Classnames however are the exact opposite. A single element may have multiple classnames, and the same class name can appear multiple times in a document.
The purpose of IDs, is to signify unique parts of your webpage (i.e. the header, the main content div, the footer), or unique parts of your content (message-number-149632).
A classname's purpose, is to describe multiple same meaning objects. (i.e. dialog, post, menu-item).
In CSS, an #id has a higher specificity value, meaning that the following:
<div id="id" class="class">Test</div>
#id { background: red; }
.class { background: green; }
Will make the div red, because ID is more specific than class.