I've been trying to get my own opinion about this issue but could not, so decided to ask.
While it seems to be well-known that the id in html is created to represent the unique element on the page, my experience is that the amount of unique elements on the page is normally quite big, especially in the custom forms. Moreover a lot of unique elements on the page are nested.
Let's take just a simple structure like this:
#content
form#search-filters
#datepicker
#search-results
When it comes to styling this peace of code you have in general two approaches (I am using scss and so are the examples):
Organize it hierarchically, e.g.
#content {
columns(8, 12);
#search-filters {
#include search-filters;
etc.
Go with the plain declarations
#content {
columns(8, 12);
}
#search-fiters {
#include search-filters;
And from my opinion it is damn cooler to have it in the first way, while it's somehow against all the logic.
The question stays even worth with the contents of that #search-filters block, given as the example above. Let's say you've used some Rails scaffolding which generated the id's for each element of the form hosting the filters, and you want to refer to that id's to provide the styling as well.
You know the the element is unique and that it will be unique in any form which extends the search-filters mixin. So you want it to have the id.
But you have to give it a class to make it logically consistent.
What is your opinion about this issue?
P.S. I've tried to read the spec about whether there are some performance difference in these two cases, but it doesn't say anything:
http://www.w3.org/TR/css3-selectors/#class-html
You generally want to have id and class selectors that are not nested, because this gives you the best rendering performance. You can read this in great details at Googles Optimize browser rendering article.
In addition having no nested CSS selectors lowers the specificity and allows you to override it for specific cases more easily.
For simple sites that have a manageable amount of style this may not matter, especially if you also handle the other speed aspects right, like put styles before scripts. In such cases I would prefer the nested style for better readability.
I don't think nesting IDs selectors will make CSS styles apply faster from a browser rendering point of view.
Also, since you already have the ID, using only that ID will make your CSS more easy to read instead of having long selectors chain.
It is different though if you plan to have different styles referencing to the same element, if the element should change it's position along the page, or maybe removed and then later recreated in another position (thus needing different selectors). In this case maybe you will need to have nested selectors, otherwise I don't see the need for that.
Related
If I have a container and a list of item, I might have the following HTML markup:
<div class="container food foodcontainer">
<ul class="list foodlist">
<li class="listitem fooditems"></li>
...
And I can style them two ways (assuming using plain CSS and not less/sass or any other helpers). First, like one normally would do:
.food { /* style */ }
.food .list { /* style */ }
.food .list .listitems { /* style */ }
Or, I can simply reference everything by a verbose, descriptive class name:
.foodcontainer { /* style */ }
.foodlist { /* style */ }
.fooditems { /* style */ }
No more cascading relationships! Is there a reason not to do this for everything (such that every element is referenced by a single class/id name)? I (and people working on the same codebase) simply do not find either to be that much better in readability; if anything, we find unique and direct names easier to grasp and also easier to search for.
There was an ancient article that generally recommended shorter, more unique selectors, for performance; in its more recent update, it's said that overall the performance has changed for the better. But how much better? Is the shorter way still faster?
.food .list { /* style */ } targets only elements with list class that are within an element with a class food.
.food > .list { /* style */ } targets only elments with list class that are direct children of elements with a class food.
.list { /* style */ } targets any elements with the class list, regardless of their parent elements.
Generally, if you want to make sure you're only targeting an element within a specific element and not any other elements that might have the same class, use the first or the second of the above, depending on your needs.
Of course, you could also give unique classes to them to avoid chaining them, but IMO there's just an unnecessary hassle of remembering which classes you've already in use. Also, I think it helps with readability, when you chain them instead of coming up with unique classes - then it's easier to see within which elements these rules apply.
I wouldn't worry too much about the performance with either of those - unless you have massive sites.
You can read about the CSS selectors here.
Well you could give a class to every element, but the point of the cascading relationships are to prevent having to give a class to every element.
For example:
a{ /* style link elements some way */ }
.some-div a { /* but in some-div they should look differently }
In this case you only have to set 1 class on the div. Else you would have had to give every link element a class in your html, which is kind of counterproductive.
Using relations you can be a lot more generic and avoid getting to the point where you end up with names like header-logo-nav-link-first. You would have to remember that class, but you would also have to write it in every element. Ever seen a footer with 50+ links? ;)
Also the more specific you are with your selectors the more priority your styling gets.
Very interesting question. Essentially, you have identified two dimensions to your class architecture. The first is the food dimension, which has a semantic meaning, and is particular to all things related to food. The second is the list dimension, which is a layout dimension, and is particular to all things related to lists and their layout.
This is a very clever way of breaking down classes. It helps prevent rules having to do with food from "leaking" into rules having to do with lists and vice versa. Your HTML becomes a clean orthogonal combination of classes from groups of classes with different meanings. In my mind, this is ideal. It follows a particular CSS design philosophy of combining smaller classes in different ways, which promotes re-use and improves readability. The alternative is "kitchen-sink" classes which are harder to re-use and harder to read. This will tempt you to use pre-processors with features like #extend, and things will go downhill quickly from there.
The technical term for defining singleton classes is "hyper-targeted". An example id Food__orange-disabled--listitem. If you go down this route, you will spend the rest of your life writing and rewriting these bizarre-looking class names. Every single change will require changes to both CSS and HTML. Proponents of this approach claim efficiency as one reason to adopt it, and this might have been an issue five years ago, but as you mentioned, today's browsers handle reasonable amounts of nested selectors without breaking a sweat.
I'm revisiting this question as I found newer and more recent articles and references.
In short, there should be little reason stopping one from using non-nested names. In fact, it might even help with both performance and maintainability.
BEM (and other similar naming schemes) tackles the maintainability issue.
And, class-centric styles help with performance.
I also want to add a few more explanations to why some of the reasons given in the other answers, or what I've seen being said else where, doesn't quite apply to argue against the case.
"This is not how CSS works."
It is true that CSS has nested relationship available, naturally as its name suggests, but that itself doesn't become the reason why we must or should use it.
"Nested relationship is easier to maintain."
This is only a "maybe" depending on the code style. Say, we have a style sheet like below:
a { /***/ }
.some-div a { /***/ }
.more-div a { /***/ }
And, we have a link somewhere in the template:
<div class="some-div ...
<div ...
<div class="some-other-div" ...
<a href="...
Now, when we look at the link in the template, we see a tag a with no classes. What styles does it have? Well, we have to go to the style sheet and search for a, and there will be many, many a's, and they can be nested arbitrarily deep.
This is just like "magic numbers" in other programming languages; the only difference is that instead of a number constant we have tag names. Searching for a single a is like searching for 3 in source code; we have to infer most information from the context.
And there is no way to do a quick search for the css selector because we don't know which parent in the ancestry tree is used in the style sheet. It could have been .some-div a or .some-div .some-other-div:last-child a.
Instead, if we classed the tag itself (e.g. <a class="some-div-link-class some-other-class" ...). It will just be a single search away.
This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 8 years ago.
Lately I'm working with a lot of Wordpress themes. When I have to edit a particular element, I usually use Firebug to see the element's name so I can change the CSS. I think I understand the difference between IDs and Classes, Classes are used for a group of elements that you want to share the same styling, and ID is usually used for a single element.
Here's the thing, I'm seeing so many elements in these Wordpress themes that are only used once, but they are assigned to a class. A good example is the website logo. Isn't the logo only used once? Shouldn't it be assigned to an ID? Why is it always assigned to a class?
Needs change often. An element/style that today you think will only be used once may be used multiple times in the future. Maybe you will have your logo more than one time on your site (for example, on your about us page). Perhaps you may eventually incorporate a second search bar. There are very few cases where you know with 100% certainty that the style will only be needed once.
Here's a good read on the subject: http://oli.jp/2011/ids/
http://ryanfait.com/articles/the-difference-between-ids-and-classes/
Ryan says
"I take a different stance than most web designers when it comes to
using ID's and classes. The vast majority of CSS coders use ID's for
any elements that are simply used once on a page. However, I only use
classes to style my websites, but, when I want to use an element in
JavaScript, I use an identifier. From a presentational standpoint,
styling elements with classes looks exactly the same as styling them
with ID's, but the flexibility of classes offers a certain appeal even
if I don't plan on using a class more than once on a page. Also, when
I see an ID in my XHTML, it reminds me that there is some JavaScript
that refers to that element. It's up to you, but so long as you
implement classes and ID's properly, it is more or less a matter of
personal choice when to utilize one or the other."
id is a unique one, but when class its not, you can you one for many selectors
ID's 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.
Any styling information that needs to be applied to multiple objects
on a page should be done with a class. Take for example a page with multiple "widgets":
There are some reasons why people prefer using classes instead of id's in CSS. (note that for javascript ID's are still commonly used).
The class element is re-usable on that page. This means that you won't have as much duplicated code with Classes as you would have with ID's.
Usually, IDs refer to something very specific, and abstracting would be tough
Any performance gains picked up by using id, is negated by adding any other selector to the left fo that id. Which mainly means that in most uses of id's you won't really have performance gains. (you could even have less performance than if you would just use a class)
Lecture about this:
http://screwlewse.com/2010/07/dont-use-id-selectors-in-css/
http://www.impressivewebs.com/css-specificity-irrelevant/
http://www.baldurbjarnason.com/notes/ids-in-css/
If you're new to web development, just use the simple rule:
If you're trying to apply style to a HTML element, use a class.
If you're trying to interact with a HTML element with javascript, use an ID.
You see more of classes because they can be reused and assigned to multiple elements.
However an id can belong to only one element at a time hence less of them.
Classes only appearing once:
Such cases like the one you identified, you may call them semantically incorrect as id is more appropriate choice for that but still it would work and it probably happens couple of times that we get to use class which only appearing once (may be while defining that class we are thinking that we can use it somewhere also but at the end we really dont), beside general habit another reason could be:
That class styling is also used somewhere else along with another class for e.g.:
.logo{
width:250px;
height:250px;
float:left;
}
.logo class is applied to logo <div class='logo'>...</div> But there is another element which also require same three properties of logo and some other also so one can reuse logo there also.
<div class='otherstyle logo'>...</div> this would apply the style of logo as well as otherstyle to it.
In some other words to sum it up. The cardinality of a class is 1...* so you can use it one and more than one time. But for id it is 1...1 you will and only use it only once.
Just got a new webpage with css for a fancy box popup from the design team;
And they don't know or don't care to look for existing classes and ids;
I need a working solution without any IFRAME
The problem is that there are already over 20.000 css lines in the main css file, and at some point something will get overwritten and the entire website will do a big BANG!
This new webpage has very common class and id names, and I am talking about almost 100 tags with css properties;
I want to know if there is a method to encapsulate this new css properties and the future ones;
And if there is a way to do this, how can it be done?
With this webpage I got lucky, I pasted the tags with content and just before this, I used the style type"text/css' tag; But i will not always be lucky;
Just because we get webpages with css code written by different people, it does not seam fair to me to create new css classes if some of the properties or names or ids intersect with each other.
I now have about 10 classes for the a tag and im most part, the properties are the same;
Use targeted rules and let the cascade take care of it for you. Put your popup in a wrapper with as detailed of a name as you like.
<div id="myPopupDivWithCommonIds">
<!-- rest of popup -->
</div>
And target your css rules to that div.
#myPopupDivWithCommonIds .error { color: bright-pink; }
#myPopupDivWithCommonIds #main { width: 93.21%; }
Etc. etc. This takes care of the css rules and prevents your new stuff from overflowing. You will have to take care to make sure none of the other rules trickle down; the best way for that is to judiciously overwrite any properties that are defined (what Pekka said). You could also go nuclear on it and include a custom 'reboot' or 'bootstrap' stylesheet and again re-target all of its rules to your new popup div (like you said, it's difficult for 20k lines of css; but including another file with the resets rules targeted to your div by appending the #id selector as above helps a little).
Oh, and that still doesn't address the problem of repeated ids technically being invalid markup and very likely to interfere with any JavaScript you're trying to run on that page.
If this sounds like a mess, well, it is. Your developers and designers have got it to that point and short of a serious refactoring, you're not going to get back to a clean solution. An iFrame may seem like a hack or impossible for your use case, but it really would clean up a lot of your correctly foreseen problems.
I'm looking for people's strategies for dealing with the inevitable need to change or otherwise adapt a CSS class to accommodate new HTML elements. I find myself in this situation fairly often so I'm hoping other people share my pain and can advise here.
Imagine you have a table of products with the nice semantic class name products. This is styled appropriately in your stylesheet. A few months down the line, your boss asks you to create a staff list on the site, "styled exactly the same as the products list".
This immediately raises an important question: what to call the new staff table. The only options I can think of are:
Give it the class name products as well. This is the quickest solution but ruins the semantics. The naming makes little sense especially to future developers.
Change the class name to something that can encompass both products and staff listings. This would negate the utility of separation of markup from style as the HTML would need changing. Also, I can't think of a single non-presentational class name that could conceivably apply to a products and a staff list.
Introduce a new class name and edit the CSS file such that .products { ... } becomes .products, .staff { ... } and .products thead th.number { font-weight: bold } becomes .products thead th.number, .staff thead th.number { font-weight: bold }, etc. Another ugly solution which will only get more complicated as time goes by.
What's the best course of action to take here?
N.B. I'm sure this problem is easily solved using frameworks like LESS (I've not used it personally) but this solution strikes me more as a 'cover-up' than an actual remedy.
If you had to put your style of the table into a few words, what would it be? I try and use that to name styles that I am gunna use in more then one place. Then I have an idea of what it will look like if I use the class.
Example:
.table-striped{}
How about Option 4:
Make a copy "products" as "staff" and continue to work on them separately as time goes on.
There are basically two schools of thought here.
1) Style that follows markup
2) Markup that follows style.
You have to figure out which one you want to do, and try to stick to one or the other. if you mix too much then it's pointless and you just have a huge mess.
In the first, you have a set markup that doesn't change. You figure out style to make it look the way you want. This is in the vein of css zen garden. It requires that your markup be extremely semantic. The drawback is that you often have a lot of duplicate styles because it's not always possible to style cleanly when using this method.
In the second, you create a lot of common styles, then adapt your markup to fit the styles. For instance, you might have a classes of "float", "thinBorder", "bold" then apply those styles to your markup. The drawback here is that if your style needs change then you have to change the HTML (or make bold not be bold, or some such). The positive is that your CSS is much more clean and maintainable.
It sucks, but you have to make tradeoffs.
Hmm...
Basically the root the problem is that your original thought of creating the first style class (.products) was too narrowly named. It is not always possible to know that you will need to reuse a significant portion of a CSS definition at a later point but based on your question it seems like you are in that line of business.
The core CSS framework does not have the way to say 'make my new style (.staff) be the same as another style (.products) with these overrides'
But I believe that the LESS framework does give you the ability to define a class (.coolTable) with all the properties and re-use these properties in multiple other class defintions (.products and .staff) quickly.
The LESS framework is not a 'cover-up' as much as an extension to the capabilities of CSS.
This is one of the things I really dislike about CSS. With all the powerful languages at our disposal, this one just seems crippled from the get-go to handle very common scenarios like yours. I too struggle with this all the time and end up either copying all the .product-related class defs to my new one or adding my new one to the .product ones. They could be pulled out later.
I need to study up on the pre-processors too because what I would love to do is something OOP-y - define b 'base class' that both .product and .mynewone inherit from and go from there.
But #3 is your best bet IMO.
I am going with first option because if everything is same & there just a change in content. So, is better to use the previous products class for staff also & Your can separately define your staff panel with the help of comment <-- staff plan-->inside the HTML page.
I would go with first option, to have class products with this block.... or maybe like class="products staff"
This way I won't be having duplicate styles(even from future aspects,when code/styles might change a lot), and any specific styles for products can be done like this by new class(or by another way of using parent class in styles to give more specificity of styles).
Yes, product class word doesn't makes much sense here, but again even for future developers, it still means you are using styles of staff class,not related to logic...
But still yes, if possible to modify markup at ease from product to some other word , I would do it.. but not as such a major requirement in these case...
Introducing individual class name for new type of content would probably be most right solution. But unfortunately current CSS syntax is far from perfect and thus forces us to be too verbose in our CSS by listing full selectors one by one.
So in practice, most maintainable solution is usually to try to find a common name for different things styled identically.
You're creating an HTML layout. Let's assume that you don't need the benefits of multiple stylesheets, that a small increase in HTML size is not a concern, and that you have a style which will only be used once. I'm often in favour of using an inline style here, as I view the repetition of your CSS class name or ID as the cost of an abstraction you don't currently need, and may not ever use.
Standard doctrine these days is to always create HTML layouts using semantic markup and CSS styles, so am I missing something here? Please let me know your thoughts.
Even if you only use a particular style once there are still benefits to keeping it with your other styles and not putting it inline. First, there is the separation of concerns that leads to improved maintainability. If you know you are going in to make only a style change, there is a single place to look for any changes. Another benefit is the self-documentation from having to type out the class name. By giving that style a name, even though it is used once, it makes the semantic code below more declarative -- you can read that not only is this random p a paragraph, it is also, say, the intro paragraph.
This is, of course, assuming that you are never going to use that particular style again. If you might than there is even more reason to factor it out into a named style. Inline styles aren't evil, but they are somewhat of a gateway drug.
Ideally your CSS should be "Object Oriented" (at least, as OO as CSS can be). You should "inherit" from classes that set common properties and create new classes when you define properties that could be used elsewhere.
Take a look at the OOCSS project which is trying to espouse these principles (or re-introduce them as it were).
To quote Welbog:
... It seems to me that "OOCSS" is just CSS that isn't written haphazardly. Much the same way you can write non-object-oriented designs in OO languages, you can easily mess up the fundamental ideals upon which CSS was created. OOCSS seems to be saying, "Let's not screw up anymore, guys."
One advantage of keeping the HTML and CSS separate is that you can re-skin the webpage without changing any of the HTML.
Steve
There are some situations in which I usually neglect creating a new class for a simple style change on a single element. It is usually pretty clear when you are doing it that there's a low-to-zero chance of you needing to apply that particular style to something else later down the road. The most common case for me is when I need something to have a particular padding/margin to be in the right place but it's not an element important enough to have its own ID.
This may not be a popular opinion here, but in those scenarios I don't think an inline style is evil.
Personally, I've found that I have an element or two and I would put an inline style in, go back and see that I need more than that element, so I'd change it to a class or forget about it and be not able to change it.
You could also try putting a certain div / page class, and write descendent styles for that in the stylesheet instead of inline elements.
Also, if you ever decide to add javascript, you won't already have a well-labeled class there and you'll need to change it.
Usually this isn't much problem with dynamically generated websites, but it can become a large problem when you go overboard and have tons of inline tags to switch out. It also can make it harder for people if they wish to disable styles for accessability etc-- you usually can overcome this by using a class.
Say, using <b style="color:red">bold</b> instead of body.products div b {color:red}.
I'm personally a fan of selectors, not using too many classes. They are more reusable, and you can edit the whole site in one place with the stylesheets.
But this is overkill <p style="font-weight:bold;font-size:1.2em; text-index:20px;">Indented Bold Paragraph</p> so it this <p class="indent bold larger">text</p> instead you can door ``<p><b></b></p>.
"A foolish consistency is the hobgoblin of little minds"
So, in this case is which is the foolish consistency? :) Why does DRY take precedence over the separation of markup and style?
Can you be sure that your CSS rule will only be used once? More over, how can you be sure that it won't need to be changed in the future, and how can you be sure that you would be the person needing to make the change? Are you sure you even need to add a class or id to target this unique element?
I guess I am having trouble seeing how adding
<input type="submit" style="border: 1px solid red;"/>
is some how "superior" to 12 or so more characters
<input type="submit" class="b-red">
.b-red {border: 1px solid red;}
or to a potentially equivalent character count
input {border:1px solid red;}
Of course there are situations where every rule of thumb can and should be violated. The question is, what do you gain from following DRY that outweighs the importance of following markup/style dichotomy?