I know we can provide styling and positioning in CSS for text box, text area, buttons etc. using "Class" , "Id" etc. attributes to identifying an element.
My question is:
How do we decide when to use a particular attribute?
Is there any advantage of using one over other (class vs Id vs other)?
Why do we have multiple ways of identifying elements? Why not have one standard way to identifying such as, lets say "Id"?
Thanks in advance
ID is used when we want a more specific selector than a class. A class can be applied to many elements, an ID only to one (a unique one at that). ID's are most specific and will (depending on your selector) gain precedence over a class. I would recommend reading up on CSS precedence: https://www.google.ca/?q=css%20precedence
You can't use ID everywhere because only one element is allowed to have a given ID, so if you want to apply the same style to five different elements, you'd have to create five different rules, which is pointless.
It's usually best to use a baseline definition for how you want certain element types to appear generally (links, lists, tables, etc.). Then if you have specific places where you want those elements to have different styles, apply a class to an element to identify that place ("navigation-bar", e.g.), and use custom styles to modify the behavior of elements within that area:
li {/* How you generally want list items to appear */}
.navigation-bar li {/* How you want list items to appear in the nav bar */}
Due to the way the styles "cascade", properties set by the second rule will override the properties set by the first because the second selector is more specific.
As far as why there are multiple ways available to select an element, it's because they're pretty much all useful at one point or another. CSS helps reduce maintenance costs because you don't have to repeat the same styling information in a bunch of different places. It can only do this if you can come up with a rule that makes it possible to match the elements you want in a variety of different situations.
The reason why we need various selectors (and not just one, using ID like you suggest) is that they are useful in different scenarios.
Element-selector (input, div, span). Useful when we want to apply some sort of styling for all elements of a certain type, indepently of its classes or id.
Id-selector. Useful when you want to apply styling to a single specific element.
Class-selector. Useful when you want to apply styling to multiple elements, indepently of what type of element they are (div, span, input). With class you can also combine styling of various classes by adding several classes to the same element.
If you were to use only the ID-selector, then you would violate DRY, since you would have to repeat a lot of CSS. Let's say you have five input-elements, that all should have the same styling applied to them. You would then have to explicitly write the ID-selector for every element:
#input1, #input2, #input3
{
/* Some styling */
}
If you later on need to add another input, you would have to modify your CSS and add a new selector for that input, so that the styling is applied to that element as well. In this case it would be better to either use a class that can be applied to all inputs. Or use the element selector and just apply the styling to all inputs.
/* Either of these would probably be more suitable */
.inputs {
/* Use a class to style the inputs */
}
input {
/* Apply styling to all elements of type input */
}
Think of an element's id like its passport number - it is UNIQUE to the one element, and can be used to apply styling to it only.
Each element can have only one ID (e.g. <div id="id"></div>)
Each page can have only one element with that ID
Think of an element's class like its nationality - it may be SHARED with lots of other elements. Therefore it is NOT UNIQUE.
You can use the same class on multiple elements. (e.g. <div class="class"></div> <div class="class"></div>)
You can use multiple classes on the same element. (e.g. <div class="classone classtwo"></div>)
When doing large projects, you may want one standard content wrapper, with different things inside it each time. In this case, the wrapper would be identified by 'class' and the things inside it by 'id'.
When applying multiple instances of CSS, the order of precedence is as follows:
Element -> applying generic CSS, for example to all 'divs'
Class -> applying generic CSS, to all elements of that class
Id -> applying specific CSS, to one element
Inline styling -> applying specific CSS, using the style="" tag within an element's tags
Related
We have a modal and full page view of our application. For the modal, we attach a "modal" class to the body, so that we can select elements based on whether or not they are contained within this "modal" class.
Several of the items we need to target have IDs. Is it bad practice to select these items like so?
.modal #child-element-with-id { ... }
The above works perfectly fine in all the browsers I've tested, but someone on the code review is complaining about it from a code smell perspective.
I know IDs are supposed to be unique and shouldn't be nested, but doesn't this constitute an exception? To me it seems like the cleanest way to target the ID, instead of coming up with separate IDs for modal and full page views.
This will work, yes. However, if you need to reuse this style for multiple elements, you should create a class.
For example if you do:
.modal #child-element-with-id { /* same style */ }
.modal #child-element-with-id-2 { /* same style */ }
.modal #child-element-with-id-3 { /* same style */ }
Then you should be making a class to avoid style duplication.
To answer your question, the jury is still out and you'll have to decide if selecting a nested ID works for your use case :)
The only issue I could see that if you move the ID to a different element, this may cause confusion and be hard to debug, because your CSS expects the ID to be nested in a class.
Styling by ID is generally frowned upon. If you have the opportunity to edit the markup, why not add a class to those elements with IDs?
You may find that once you have introduced a highly specific selector (0, 1, 1, 0) you may end up having to add to it later for something even more specific – this is the scenario we try to avoid.
…instead of coming up with separate IDs for modal and full page views
I would reconsider this setup and add classes onto the elements with ID's. If you are already styling those elements by #id it's quite easy to swap the CSS selector to a class. If you find it's not easy to style those #ids now that they are classes - my point may already be proven :)
Hope that helps!
This will probably be an extremely easy question to answer, but I am trying to create a one-stop-shop for setting up property values from SQL and would like to know an answer to the issue that just came up in brainstorming:
If you set a parent (let's say a form) to be Read-Only but set an object (lets say a button) in that parent to NOT be Read-Only, will the button be read-only? Also, what If the parent or child had !Important included?
I am trying to set up a priority system so users can set up these kind of property values without running into issues where unexpected things do not happen.
readonly is not a css property, thus no style. It goes directly into the html tag.
The key buzzwords for you to search are css inheritance and css specifity.
For a quick overview: Yes, there are fixed rules. Not every property is inherited. You can look them up e.g. in the MDN CSS Reference.
Which css rule kicks in depends on where you place the style rules and how specific your selector is.
Cascading order (source):
Inline style (inside an HTML element)
External and internal style sheets (in the head section)
Browser default
Specifity is like a score system. The rule with the highest score (=highest specifity) applies.
ID, e.g. #paragraph {...} (100 points)
Class, e.g. .redparagraphs {...} (10 points)
Tag, e.g. p {...} (1 point)
So the rule div p span {...} would have a score of 3 points, because of three tag selectors.
#wrapper .centered #main .fancynews .withoutborder p {...} would have 231 points and so on.
If two rules have the same score (specifity), then the last one processed counts (stylesheets are processed from top to bottom).
The "quick and dirty" trick for applying a style is to add an !important to the rule like
.alwaysredtext { color:#F00 !important; }
This will override whatever color rule you made and whereever (as long as they do not also have an !important). This is not recommended due to later maintainability problems.
p.s.: Don't miss the Specifity Calculator where you can enter and compare several selector rules and see which one "wins".
Only <input> and <textarea> elements support the readonly attribute, so not, what you are describing is not possible.
I have a custom HTML5 tag called <scroll-content>. This tag actually gets created and inserted for me by a framework in certain places inside of my HTML file. Now I would like to modify the CSS of this tag so inside my CSS file I went:
scroll-content{
overflow: hidden;
}
It did what it was supposed to, but is this the proper way of styling the custom tags?
I can't add a class to them because I do not create the tags, the framework does, so I can't access them in my code and I would like to avoid using Javascript to find these tags and adding classes that way.
I would prefer to know the standard/safest way of modifying custom tags.
You can apply CSS to custom elements just like you can to standard HTML elements.
There's nothing wrong with scroll-content { ... }, as written in your code.
A Little Background
The browser, at a basic level, has no clue what elements exist. It doesn't recognize anything... until it is exposed to the default style sheet (sample).
The default style sheet introduces the browser to HTML elements.
Custom elements can therefore be defined as elements that are not included in the default style sheet. (Elements that exist, but are unsupported by the browser, could share this definition.)
Custom elements could, however, be introduced to the browser in author styles.
Here's something important to consider:
If the browser doesn't recognize an element (i.e., it's not in the default style sheet), it will apply CSS initial values.
6.1.1 Specified
values
User agents must first assign a specified value to each property based
on the following mechanisms (in order of precedence):
If the cascade results in a value, use it.
Otherwise, if the property is inherited and the element is not the root of the document tree, use the computed value of the parent
element.
Otherwise use the property's initial value. The initial value of each property is indicated in the property's definition.
As outlined above, if an element is unrecognized (#1 & #2 don't apply), use the initial value from the property definition (#3 applies).
So in your case:
Your custom element is: <scroll-content>
Your CSS is: scroll-content { overflow: hidden; }
You say in your question that this code does what it's supposed to do. But unless the framework you mention provides additional styles for custom elements, it cannot work (demo).
Here's why:
Since <scroll-element> is not in the default style sheet it will use CSS initial values.
Well, the initial value of the display property is inline.
But the overflow property only works on block elements.
So there's no way this HTML/CSS combination could work – the overflow property would be ignored, as would height, width and any other properties that don't apply to inline elements.
A custom element would need to have display: block applied for overflow to work (demo).
Similarly, the only reason body, div, h1, p, ul exist as block elements is because they are defined this way in the default style sheet (sample).
So, putting aside the arguments for and against custom elements, here's the bottom line:
Add display: block to your custom elements and you're good-to-go.
Cannot exist standard tags with a hyphen "-" in his name, so there is not such problem.
It would be preferable if you can avoid using custom tags since you never know when those tags may become standardized or have a specific usage at some point.
I think it would be safer if you create a class to that custom tag, something like:
.scroll-content{
overflow: hidden;
}
This should do it.
I always was told to take out multiple properties in your css that you use more then once, and add them all in one rule. Like below. (please excuse the poor example)
I always seen this:
.button, .list, .items { color: #444; }
With multiple rules, can't that leave a lot of clutter?
Only in css tutorials and examples Ive seen this:
.someColor { color: #444; }
And in the css, just add another class of '.sameColor'. (div class="button someColor")
I've never seen this and feels like it would leave less clutter in your CSS. Would this be okay? Or do you think it could leave with more clutter in your HTML ?
Try to name your classes independently of their visual effect. It is a nature of CSS to play with the design and layout without having to change the HTML. Class names such as .someColor or .left-sidebar are a bad practice. Colors and position can change.
And also apply rules to semantic HTML elements rather than adding classes on all different divs and spans. It should be obvious, although many people get this wrong.
CSS is a limited set of rules and that makes it a perfect creativity stimulator.
It's all based on personal preference. I've tried both methods and prefer the second method you listed, except with more generic class names such as middleParagraph or headerGraphic so it applies to an area rather than a specific color because colors can change.
Good classnames and IDs are the first place you should optimize. THEN move onto multiple class names.
Multiple classnames can help out quite a bit though, consider:
<div class="leftColumn">Left</div>
<div class="rightColumn">Right</div>
<div class="middleColumn hasLeft hasRight">I have padding-left of 210px and padding-right of 210px</div>
<!-- alternatively, you could have -->
<div class="rightColumn">Right</div>
<div class="middleColumn hasRignt">I have padding right of 210px</div>
<!-- or -->
<div class="leftColumn">Left</div>
<div class="middleColumn hasLeft">I have padding left of 210px</div>
<!-- or -->
<div class="middleColumn">I have no padding</div>
and your css
.leftColumn { width:200px; float:left; }
.rightColumn { width:200px; float:right; }
.middleColumn.hasLeft { padding-left:210px; }
.middleColumn.hasRight { padding-right:210px; }
The result is floated right/left columns and the center area compensates for them with padding. This means you can style your middleColumn how you want to (e.g. .middleColumn .otherCoolSelector ).
It's perfectly acceptable to apply multiple classes to HTML elements. The trick is to be judicious; I usually find that when I do this, the additional classes are additions or exceptions to the basic styling being applied. For example, here are some classes I occasionally add to an element that already has a class:
error -- to style the current element if the user entered invalid data
first -- to style the first element in a list or in a table row, e.g. to suppress padding-left
last -- to style the final element in a list or in a table row, e.g. to suppress margin-right
even -- to apply zebra-striping to alternate elements
hidden -- to hide an element if it's not currently relevant
These extra classes are typically generated dynamically with a server-side language like ASP.NET or PHP. They can also be added or removed on the client side with JavaScript, esp. with a library like jQuery. This is especially useful to show or hide elements in response to an event.
There are a lot of good answers here. The trick is finding out which one fits your situation best.
One thing to consider is your markup size. In a high-traffic situation, your markup size is critical to the speed of your page loads...every byte counts. If this is the case for you, then you may want to create more CSS classes and put less in your markup. That way, the client is caching more and your website is serving up less.
What you're suggesting is a bit like an in-line style, e.g. style="color:#444". So if you want to change the color of your element you'd have to make a change to the html, which means you've defined style as part of your content. Which is exactly what css is supposed to avoid.
Imagine if you'd included 'someColor,' multiple times across multiple html files and you decide some of these elements shouldn't have 'someColor,' after all, you've got a lot of files to go through.
I'd probably avoid the list option too, if I'm making a component, say a button, I want to find .mybutton class in my css file and see all the rules for that component, without having to go through all sorts of unhelpful global classes. Also if someone comes along and changes the color in our global class he may break my button, where as if the button controlled it's own styles it can't be broken in this way.
In CSS we can use both ID and class. is there any pros and cons if i use Class always instead ID in terms of Semantic, Web standards- W3C , SEO , Accessibility and future maintainability?
One big difference: in CSS, a class has a lower importance level than an ID.
Imagine that each specification in a CSS declaration added a certain number of points to that declaration's value. Let's say the points go something like this (totally made up, but whatever):
Tag name ('a', 'div', 'span'): 1 point
Class name ('.highlight', '.error', '.animal'): 10 points
ID ('#main-headline', '#nav', '#content'): 100 points
So, the following declarations:
a {
color: #00f;
}
.highlight a {
color: #0f0;
}
#nav .highlight a {
color: #f00;
}
are worth 1, 11, and 111 points (respectively). For a given tag, the declaration with the highest number of points that matches it "wins". So for example, with those declarations, all a tags will be blue, unless they're inside an element with the "highlight" class, in which case they'll be green, unless that element is inside the element with id="nav", in which case they'll be red.
Now, you can get yourself into tricky situations if you're only using classes. Let's say you want to make all the links in your content area blue, but all the links in your foo area red:
.content a {
color: #00f;
}
.foo a {
color: #f00;
}
By my previous (made up) scale, those both have 11 points. If you have a foo within your content, which one wins? In this situation, foo wins because it comes after. Now, maybe that's what you want, but that's just lucky. If you change your mind later, and want content to win, you have to change their order, and depending on the order of declarations in a CSS file is A Bad Idea. Now if, instead, you had the following declaration:
#content a {
color: #00f;
}
.foo a {
color: #f00;
}
Content would always win, because that declaration has a value of 101 (beating foo's 11). No matter what order they come in, the content declaration will always beat the foo one. This provides you with some very important consistency. The winners won't arbitrarily change based on changing orders in the file, and if you want to change the the winner, you have to change the declarations (maybe add a #content in front of the .foo declaration, so it will have 111 points).
So basically, the differences in values are important, and you get a lot of inconsistency and seemingly arbitrary winners if you just use classes.
I know i'm not the 'norm' here and i'll get thumbed down for this... but i use classes exclusively and only ever use ID's for scripting :)
This creates a clear line of seperation of designer and coder related tweaks and changes, which is very handy for us!.
Also we have some .NET web form coders (even though we are moving all sites to MVC) and as .NET controls take over ID's to script them dynamically using ID's for CSS is a pain... i'm not a fan of using #ct00_ct02_MyControlName in css files and even if i was changes to code can break the CSS! Classes works GREAT for this.
Some PHP libs others in the company are using also need to use dynamic ID assignment, this creates the problem here too. again Classes work GREAT here.
As more and more of these dynamic outputs and languages use up the ID's (for exactly what they are really intended for... identifiing an element to work with it) it can be more and more of a pain to work with IDs in CSS.
It's seems to me that everyone wants to use them simply cause they think they should, becuase they are 'there', i offer the idea that ID's are not there at all for CSS and their use in CSS is just there as an extra helper via the selector and their real use is scripting.
There has not been a single instance where i needed an ID for css use or even a single instance where it would have been eaiser.
But perhaps i'm just used to it and thats why? My HTML output is small, my CSS files small and direct. Nested elements work in all browsers as i expect, i dont have issues and can create complicated nicely rendered pages. Changes take mere minutes as i can apply multiple classes to an element or make a new one.
ID's for scripting, CLASS for css... works a treat.
Obivously there is no major issue (Even in a team of designers and coders) in using them both for css as we all get used to what we get used to :) but the way we work it outputs the expected results fast, and noone can step on anyones toes even in anonomous sharing enviroments.
My biggest one would be from the future maintenance point of view. Not only is it nice to know that a style is only used for one element on a page, but if you ever start integrated javascript into your page its nice to be able to access elements quickly using their IDs rather than try and access them by their class's.
If you're using a decent javascript library (like prototype or jQuery) then no, I can't think of any technical reasons why this would matter. However, it might help your own internal thinking and consistency to think separately about whether it is an attribute-like collective characteristic (=> class) or a specific item (=> ID).
Use id when an element is unique on a page and you always expect it to be. Use class when multiple elements will be assigned the value of the attribute. It's true that it may not make a big difference from a purely CSS perspective, but from the JavaScript or Selenium perspective, it's a big deal to be able to uniquely identify elements by their id attribute.
In simple we can define id and class as below
ID = A person's Identification (ID) is unique to one person.
Class = There are many people in a class.
Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.There is no hard rule on when to use ID and when to use Class. My suggestion is to use class as much as possible for maximum flexibility, with the only exception being when you want to use Javascript's getElementByID function, in which case you need use ID.
IDs are good for elements that need to be accessed from JavaScript. But the IDs must be unique in the page according to w3 standards, that is:
you cannot have two <div id="Header"> in one document
you cannot have a <div id="Header"> and <p id="Header"> in one document
Class names are good for elements that do not need to be accessed from JavaScript (although it is possible to do so). One class name can be used for multiple elements, and one element can have more than one class names attached to it. Class names therefore allow you to create more "generic" css definitions, for example:
<div class="column">
<div class="column left-column">
<div class="column right-column"> -- all three can be in the same document
You can mix IDs and classes together.
To summarize: use IDs for specific cases; class names for generic cases; and cascad classes for elements that share some general properties but not all.
See following:
CSS Best Practice about ID and Class?
For SEO: It will make absolutely no difference to seo at all.
You should choose names that reflect the semantic content of that section. eg: id="leftMenu" class="footerNotes"
Don't use any underscores in your class and id names (common mistake).
The only difference between classes and ids, except for the fact that an id MUST be unique and a class does not, is that the browser can use an element's id for navigational purposes. For example, this page has a logo with id="hlogo". If you append to this page's url the hash #hlogo, like this https://stackoverflow.com/questions/1878810/is-there-any-pros-and-cons-if-i-use-always-css-class-instead-css-id-for-everythi#hlogo, the browser will automatically scroll to the logo.