Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I read an article where it was recommended that we should ONLY use classes in our markup and only use ids when we need to refere to it from javascript (as it is easier to attach functions to ids)
At the moment I only use classes when I have more than one element that needs the similar style. However the article (which I THINK I read - but have no reference) stated that we should use classes throughout
I would do this:
<header id="banner"></header>
Where as the recommendation was :
<header class="banner"></header>
(even though the banner is only used once per page)
is this the new "good practice"?
Thanks
As far as I know you are correct, you should use classes when you need to style multiple elements and IDs when you are only styling a unique element.
I think you may have stumbled on an article about object oriented css. The basic idea is that you should think of the style as a sort of abstraction which is linked to your markup via classes. I find it to be a good technique for keeping things organized, but, as with all techniques, it's not a universal hard and fast rule. I see no problem with linking style to markup with ID's, as long as that makes the most sense.
It's what "makes sense" that is the real tricky thing to define.
ID Attribute, Definition and Usage
The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).
The id attribute is most used to point to a style in a style sheet, and by JavaScript (via the HTML DOM) to manipulate the element with the specific id.
Read more about it here!
CLASS Attribute, Definition and Usage
The class attribute specifies one or more classnames for an element.
The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class.
Read more about it here!
So, you can style using either Id's your Class's, just knowing that the class can be re-utilized on other elements across your web page, the Id must always be unique.
The reason to tell that Class's are the best attribute to utilize to apply CSS is because you can have generic class names and use then a lot through your web page, thus simplifying and reducing the time spend coding :)
Simple example:
HTML
<div id="theUniqueID">
Hello!
</div>
<div id="theUniqueIDTwo">
Hello Again!
</div>
CSS
#theUniqueID {
font-size: 15px;
text-align: right;
}
#theUniqueIDTwo {
font-size: 15px;
text-align: right;
}
Can be reduced to:
#theUniqueID, #theUniqueIDTwo {
font-size: 15px;
text-align: right;
}
And can be generically utilized across the document like this:
.format_01 {
font-size: 15px;
text-align: right;
}
Having then the HTML like:
<div class="format_01">
Hello!
</div>
<div class="format_01">
Hello Again!
</div>
<div class="format_01">
Hello Again and Again!
</div>
Ps:
Sorry for the overkill answer, but this allows others with less knowledge to learn as well.
Basically you should use id for unique elements that means if you want to keep an element on the page that won't be appear on the page twice then you should use id and to style a group of elements with same style or to keep some elements in the same group you should use class.
But remember, you can also use class for a single a element but you can never use an id for more than one element on the page.
For example, getElementById or $('#idOfElement') (using jQuery) returns a single element but getElementsByClassName or $('.idOfElement') (using jQuery) returns an array of matched elements. So if you have more than one element on the page using same id then you'll get only the first element that have the id, so never use id for more than one element.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
In an online tutorial, I was recently told to create a class for nav elements called "nav". I'm a beginner in CSS, but is it just me, or is this redundant/confusing/bad practice?
NO it's not redundant.
YES it's redundant if you think in your specific case you're fine with nav{ /*blaah blaah*/ }
<nav> is a Semantic HTML5 tag that represents toward SEO a navigation. A navitagion is all you want it to be. So in the case you have multiple nav elements in our page and you're OK to target-styles directly the tag element using nav I'll be glad to see that.
It's not redundant. The DOM element nav is different from the CSS class nav.
If you wanted to style this element by class, you would use this style declaration (for example):
.nav { background-color : #F00; }
if it were styled by element type it would be:
nav { background-color : #F00; }
This may seem trivial, but that period . makes a difference. It means you are identifying the item by class and not by element name. If you use the class syntax (with the .) then you could also write:
<div class="nav"></div>
This would show with a red background if you included the class definition, but not if you styled the element type directly.
In simple applications you may be able to get away with directly styling element types (e.g. <nav>) as opposed to classes (e.g. class="nav"), but as you get more complex layouts you are going to want to use classes. Additionally, if you use a selector-based library like jQuery, or document.querySelect() you may have good reasons for specifying a class.
If you truely can know that all <nav> elements can be styled the same in all your pages, then by all means just use the element selector, but to leave yourself flexibility it's best to use classes.
I am trying to use one CSS class to many DIV. Is it a good practice? or else are there any disadvantages of doing that. because in VS it says "another object already uses this ID", not an error message but a warning.
CSS classes are meant to be reused. CSS IDs are meant to be used uniquely on a component. Are you sure you're using a css class?
There is nothing wrong with styling multiple divs at the same time. This is actually expected and not many people do that. To style all divs;
body {Body Code Here;}
div {Div styling here;}
Styling all div's with one class;
body {Body Code Here;}
div.YourClass {Div Styling Here;}
Notice how there is no space between the div and selector(.) That specifies a class in any div where as div .YourClass will search in all divs for a class. IDs are different than Classes, you can have multiple Classes on the page but only 1 ID on the page. To fix that message, make sure you are using Class instead of ID and search the page for that ID and if it comes up twice or more, thats your problem. Again Classes are reusable and IDs are single-element selectors. Hope I helped!
In css, class is meant to be reused, so it is ok. In case you don't know about id, id in css is meant to be used noce. But nowadays, I've seen few people use class all over place even they just use it once. So, just keep your markup and styling clear, use class or id in your way if you work alone [ personal project ] and keep it persistence when working alone or in a team.
html
<div class="class1 class2">afd</div>
<div class="button class1">asffsdf</div>
css
.class1 { /* styling your class1 here */ }
It is absolutely fine to use the same class for many elements in CSS. Be careful not to do the same for the "id" attribute, which really should only be used for a single element as it is considered a unique ID.
You can use same CSS class for any number of elements, but ID must be unique for each and every element in the page
ID is somewhat different from class. You can have multiple classes on page but ID should only be used once. Do follow best practices :)
i know... this information is not what exactly you want as answer but may be of some little help :)
example:
div.className { } //covers all div with a particular classname
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.
I am finding it useful to define 'marker' css styles such as 'hidden' or 'selected' so I can easily mark something as hidden or selected - especially when using a tag based technology like ASP.NET MVC or PHP.
.hidden
{
display:none;
}
.newsItemList li.selected
{
background-color: yellow;
}
I don't especially feel like reinventing the wheel here and wanted to know what other things like this are useful or common - or if there are any pitfalls to watch out for.
Should I look at any specific css frameworks for other things like this? Plus is there a name for this type of css class that I can search by.
I agree with the other posters who say only to define what you need, rather than bloating your code with a bunch of unnecessary classes.
That being said, I find myself using the following on a constant basis:
.accessibility - visually hide elements, but keep them intact for screenreaders and print stylesheets
.clear - tied to Easy Clearing
.first-child and .last-child - easily assign styles to the first/last item in a container. This has been a lifesaver many times, and I prefer it over the poorly-supported :pseudo selectors
.replace - tied to Phark IR for transparent image replacement
Finally, I dynamically assign .js to the <html> element with
<script type="text/javascript">if(h=document.documentElement)h.className+=" js"</script>
This will allow me to define .js (rest of selector) styles to target only browsers with JavaScript enabled.
Let me give you an answer from a very novice web developer who has recently considered using CSS classes as "markers". Please don't take this as a definitive answer, as I may be completely wrong, but look at it as another point of view.
I was going to use some marker classes, too. I created one called .center to center the elements in a DIV tag. However, I was struck with the idea that I'm looking at CSS all wrong. I reasoned that CSS is supposed to define how an element is to be displayed without having to change the HTML page. By using marker classes, like .center for example, I would have to change BOTH the CSS and HTML if I wanted that DIV tag to be right-justified next month. So instead, I created a .latestHeader class (the DIV is to hold the "latest information" such as a news item), and in that class I set the text to align center. Now, when I want to change the justification of the text, I simply change the CSS for that DIV and I don't have to touch the HTML.
In regards to your question about CSS frameworks...
Personally I've always found the W3C has the most complex but also most accurate answer to any CSS question.
After many years of programming and playing around with CSS/HTML/PHP I agree with the above comment.
There is no harm in defining a marker for something to be centered or right-aligned using something along the lines of a '.center' or '.righths', but keep in mind as above that if you want to change a whole slab of text your work will be increased because you have to edit both CSS and HTML.
Defining the format for a whole section will mostly likely work out more logical, because if you want to change the section months down the trail, you just have to edit the format of one CSS declaration as opposed to editing each individual article.
CSS was however designed as the ultimate styling language which could allow an administrator to make a website look exactly what they want it to. Keep in mind though that excess CSS will increase the load on a server, will increase the time before your client sees your page and in line with the 'feng shui of web design' it is possible to go overboard with too much styling.
You should really grow this list on a need basis instead of soliciting a list of generic classes across the board--you'll only end up with bloat. If you want to avoid reinventing the wheel the look into some CSS frameworks (blueprint or 960). In some respect, generic classes like .center { text-align:center } do have some level of redundancy but often times they're needed. For example the following pattern which is all too common but should be avoided:
element.onclick(function(e){ this.style.backgroundColor = 'yellow' }
That's bad because you really ought to be using:
element.onclick(function(e){ this.className = 'highlight' }
The latter allows you to modify your styles by only touching the CSS files. But if a CSS class name has only one style element then you should probably avoid it because it doesn't make any sense to have it (.hidden in your example) and call it directly instead:
element.onclick(function(e){ this.display = 'hidden}
I often find myself keeping two classes in all of my stylesheets: "center" (which simply applies text-align: center;, and a float-clearing class that applies clear:both;.
I've considered adding a "reset" statement to all my styles, but haven't had a need for it yet. The reset statement would be something similar to this:
*
{
margin: 0;
padding: 0;
}
I reuse these often enough to include them in just about everything. They're small enough so I don't feel they bloat the code at all.