How does CSS work with lots of same classes? - css

I'm curious about what impact does CSS have in the following situation or rather how does CSS change style for many same classes in general. I'm not particulary good at phrasing questions because English is not my first language and I'm not very familiar with all the programming terms, that's why I couldn't find anything online.
Let's say I have very large number of divs <div class="my-div"> and .my-div { background-color: red; }
How does CSS handle this situation? Does it style all div-s in one simple round or is there something more complex involved?
Im asking this because I can't decide if to use small .png images or HTML elements and CSS for map's markers, I would prefer the last one in order to use :hover and other neat CSS tricks.

Well, for all general purposes the browser will handle a large number of elements quite effectively. And yes the CSS styles all the divs with one simple round.

Related

Best Practices for Cleaning up Existing CSS/unused styles [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Is there any way to find unused css in a website?
I'm looking for best practices on how to clean up existing style sheets and also inline styles. I have some style sheets in existance, and I'd like to clean up the bloat so they are more maintainable in the future.
Can we make this a community wiki?
There is so much that can be said about best-practice methods for CSS. I'll try to stick to the main points.
Use a CSS reset.
Try to remove really general CSS statements like h1 {} and #container em {}. You're much better off using h1.section-title and #container em.important {}, because that way if you choose to use h1 or em a different way somewhere in your document, you don't have to worry about overriding any existing code.
Don't be too specific in your CSS selectors if you don't have to. You really only need to have high degrees of specificity if being in a specific section changes how the element is going to be displayed. Otherwise, to make your code for your block class reusable, #container .content .block ... could be reduced to .block ... in many cases.
Look for commonalities in your CSS and see if you can create reusable classes. If you have similar blocks class="favorites" and class="popular", turn it into class="block block-favorites" and class="block block-popular", and put the commonalities into .block.
Get in the habit of making areas in your CSS have an auto-width (can be done implicitly) so that they grow to the width of your containers. This makes it incredibly easier to move sections from a narrow portion of your website to a wide portion of your website without having to change any code.
Commenting your code and breaking it down into sections usually helps make code more readable.
You'd be surprised how much cleaner your code looks when you implement more powerful CSS selectors. Most of them are cross-browser compatible (IE7+).
Some valuable resources: When can I use... - Quirks Mode on CSS Selectors - w3 on CSS Selectors

Multiple classes in body tag, multi-dimensional css structure or blueprint for insanity?

This question is about an approach to css structuring, and so is more discussion oriented.
I'm working with some outsourced css where the body tags have multiple classes assigned, up to half a dozen. (To make things a little worse, none of the css selectors include an html tag which is making it confusing to analyze the css.) These body classes are then used to modify classed or id'd widgets within.
It seems like this approach is like adding an additional dimension to the css, perhaps in some attempt to create a structured css approach. Documentation might have helped, had we been provided any.
This differs from my approach where widgets are styled primarily via id'd divs, perhaps extracting the more generic elements into a class, i.e. div#MyWidget.widgets.
Any ideas on whether such an approach is maintainable, especially considering I am dealing with websites with thousands of pages including tons of legacy stuff, all done by different people with different skill levels? Thanks...
I find nothing particularly wrong with this approach, provided you are conceptually using the body tags to apply very general style rules. The higher up the class is in the DOM, the more generic it should be.
It's hard to answer specifically without examples. One I frequently use is to turn the URL segments into classes for body tag in my pages, for relatively small sites:
// mysite.com/users/show/
<body class="users show">
<div id="Content">
...
</div>
</body>
I use this almost exclusively for overriding default styles on very specific pages:
#Content {
width:500px;
}
.users.show #Content {
width:600px;
}

Is there any way to find unused CSS in a website?

Is there any way to find unused CSS in a website?
I'm trying to clean up a project I just inherited.
Dust-me Selectors is a Firefox plugin that finds unused selectors.
I just ran into this and remembered your question: http://github.com/geuis/helium-css
Chrome 59 has built-in coverage display for CSS and JavaScript since 2017-04: https://developers.google.com/web/updates/2017/04/devtools-release-notes#coverage
You can enable it by opening the dev tools, then the command menu (Cmd+Shift+P on Mac or Ctrl+Shift+P on Windows and Linux), and then type "show coverage".
There is so much that can be said about best-practice methods for CSS. I'll try to stick to the main points.
Use a CSS reset.
Try to remove really general CSS statements like h1 {} and #container em {}. You're much better off using h1.section-title and #container em.important {}, because that way if you choose to use h1 or em a different way somewhere in your document, you don't have to worry about overriding any existing code.
Don't be too specific in your CSS selectors if you don't have to. You really only need to have high degrees of specificity if being in a specific section changes how the element is going to be displayed. Otherwise, to make your code for your block class reusable, #container .content .block ... could be reduced to .block ... in many cases.
Look for commonalities in your CSS and see if you can create reusable classes. If you have similar blocks class="favorites" and class="popular", turn it into class="block block-favorites" and class="block block-popular", and put the commonalities into .block.
Get in the habit of making areas in your CSS have an auto-width (can be done implicitly) so that they grow to the width of your containers. This makes it incredibly easier to move sections from a narrow portion of your website to a wide portion of your website without having to change any code.
Commenting your code and breaking it down into sections usually helps make code more readable.
You'd be surprised how much cleaner your code looks when you implement more powerful CSS selectors. Most of them are cross-browser compatible (Internet Explorer 7 and later).
Some valuable resources: When can I use... - Quirks Mode on CSS Selectors - w3 on CSS Selectors
Answer moved from:
Best Practices for Cleaning up Existing CSS/unused styles
To add to #cweiske suggestion, Google Chrome has a no nonsense way of uncovering where your "unused" and "never will be used" selectors are.
I have posted a screen capture of how to launch the CSS Coverage tool with step by step markers.
It is a reliable way to figure out where you really are not using stuff.

CSS coding style [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Are there any good CSS coding style/standards?
Here is a good one:
http://www.phpied.com/css-coding-conventions/
But the important thing is to pick something and stick with it for consistency.
I agree with most of the points at Andrew Hare's link, but I strongly believe
.class-name {
color: green;
}
is inferior to:
.class-name
{
color: green;
}
on the grounds that:
.class-name, .class-name2 {
color: green;
}
or:
.class-name,
.class-name2 {
color: green;
}
are considerably less obvious to grep or read than:
.class-name,
.class-name2
{
color: green;
}
There's no standard standard, as it were. There are most certainly plenty of in-house standards and conventions. And there are certainly known best practices.
I stick to the following:
Structure your CSS according to it's purpose
That may involve separating out CSS concerns into different files (layout.css, colors.css etc). This may just as well involve clearly dividing up a single CSS file into clear sections along the same lines.
Be as specific as possible
Selectors have differing weights. ID-based selectors are more specific than class-based selectors. Chained selectors (e.g. body div#container div#content p) are very specific indeed.
Start out being as specific as you can, even if it appears you're being too specific. It's quite easy, later down the line, to merge together two very specific style definitions by removing one and making the other less specific.
A style definition with loose specificity may target elements you did not intend in ways that are not immediately apparent or obvious. I think this is the most common cause of CSS frustrations ("Why on earth will this div not let me set a top margin?")
Always specify every single style you wish to apply for a given defintion
For example, if you want all your paragraphs to have pink text, set the text colour to pink and also set the margins/padding/background colour/font and so on.
Don't rely on browser defaults to be suitably consistent. Certainly for the most commonly used elements the main browsers tend to use very similar if not identical default styling.
If you set all the relevant styles yourself you know what the end result should be.
If you only set those styles that are most immediately obvious, the end result will be (most likely) a combination of the browser defaults and your styles. This will eventually catch you out at some point. I think this is the second most common cause of CSS frustrations.
Use ids for styling unique elements
It's generally a good idea to apply an id attribute to any unique element that is going to be interacted with in any way. For CSS this will let you apply suitably specific styles more easily.
Use an id on a unique page
Pages that are significantly different in style and layout to the majority (homepage, search results, 404) should have an id on the body element. This gives you the specificity you need to ensure that your careful homepage styling doesn't get affected by styles you later apply to some internal content page.
Pretty coding style VS site speed
I've been working with pretty huge CSS files, and found out some pretty interesting things that I've never read about before.
#import
One thing is using #import. That's actually a bottleneck - by going away from using #import completely, the site got a lot more snappy.
#every .style { in one line }
When the browser reads a document, it reads line by line, so by switching from my pretty coding style to this, I accomplished 2 things;
A even more snappy site
Less scrolling, better overview. Why? Cause I first scroll down to find the style I'm going to work with, then it's all in the same line and it's not hard to scroll your eyes along the line to find what you're looking for.
The main good coding style is to actually separate css files according to their goals.
See Progressive Enhancement.
That way, whatever coding convention you will choose, you will have consistent and manageable separate css files... easier to debug.
When I code in CSS:
In first part I write the class and id
In last part I write the general element (p, font, etc) because the class and id have more importance for inheritance
I write comment if I want a particular behaviour with IE or with MoSE Browser
You can see some example in CSS Zen Garden
Generally I insert the most important elements over the other: if there's
p.important{/*features of a class*/}
p {/*features of a general element */}
Reading the CSS file I know the format rules before about the most particular elements, after the rules about the most general elements.
It's an habit in programming Java.
Put your css rules (ex: "color: red;") in alphabetical order and also put your selectors (ex: "div { color: red; }") in order they appear in your markup. Separate code for structure from skin.
Just from experience I used to write quite long CSS style sheets. Now my style sheets typically are half a page.
So keep it simple(KISS), line based (greppable) and keep it compact (use font: instead of font-size etc etc.).
Also I highly recommend using CSSlint to check your code for fluff.
Check Sass out. It's a template language for CSS that makes your source code DRY:er and mucho easy to read. Even if you're not using ruby you can use it for this task and automate the building of your css files from Sass source. And there are probably Sass implementations in other languages too.
There's probably loads. At our work we use the following:
/* =div a comment about my div */
div#mydiv {
border:1px solid #000;
}
The =div allows us to search against all div elements by using the search functionality. There's loads more though, I've used many different variations of this in the past.
In addition to what others said, remember that the C stands for 'Cascading', i.e. subelements inherit from top level elements. Sound simple and straight away. But I have often seen CSS files that contain redundant declarations, e.g. for font styles. This makes a CSS more complex and hard to maintain.
So before you add something to your CSS make sure that it is not redundant, i.e. check parent elements and remove redundant declarations from children.
Given this you should organize your CSS in a way so that high level elements (like declarations for the body class) are mentioned first and more specialized elements last.
This might also be helpful, a few tips to keep your CSS styles DRY - as in "Don't Repeat Yourself" link text
I will strongly recommend looking at Less: http://lesscss.org
While not really a standard, it has been gaining a lot of momentum recently. Less is css extension that runs in the browser bringing variables and functions into the language and therefore allowing templating.

is using class names like 'right' considered bad practice?

If I have class names such as "left", "right", "clear" and xhtml like
Continue
With CSS like
.right {
float: right;
}
I know it's not a semantic name, but it does make things much easier sometimes.
Anyway, what are your thoughts?
I don't think that's a very good idea. Now when you (or a future maintainer) go to change your website layout, you'll either have to change .right to {float:left;} (obviously a bad idea) or go through all your HTML files and change right to left.
Why do you want that particular link to be floated right, and the other .continueLink's not to? Use the answer to that question to choose a more descriptive class name for that link.
css is about presentation of the structure of your html page.
Meaning its classes should represent the structure of the document ('article', 'extra-links', 'glossary', 'introduction', 'conclusion', ...).
You should avoid any class linked to a physical representation ('left', 'right', 'footnotes', 'sidenotes', ...), because, as the Zen Garden so clearly illustrates, you can decide to place any div in very different and various ways.
The purists will say don't do it, and the pragmatists will say it's fine. But would the purists define .right as float: left?
It might be advisable to avoid names that are the same as values in the CSS specs to avoid confusion. Especially in situations where multiple developers work on the same application.
Other than that I see no problem. I would qualify the right or left name like this: menuleft, menuright etc.
Being a purist, I say no don't do it. For reasons mentioned earlier.
Being a pragmatist, I just wanted to say that never have I seen website rework that involved pure html changes without css, or pure css without html, simply because both parts are being developed with the other in mind. So, in reality, if somebody else would EVER need to change the page, I bet my salary they will change both html and css.
The above is something that collegue purists around often tend to ignore, even though it's reality. But bottom line; no, avoid using a className such as "right". :-)
.right and other classes like that, certainly makes it quick to write create a tag with a float:right rule attached to it, but I think this method has more disadvantages than advantages:
Often a class-style with a single float:right; in it will lack something, your example wil only float right if the other class rule contains a display:block in it, since an "a" tag is not a block level element. Also floating elements more often than not needs to have width an height attached. This means that the code in your example needs additional code to do what it says, and you have to search in two places when you have to change your css.
I tend to style my html by dividing the page into different div-tags with unique id's, and then styling elements in these div by inheritance like this.
div#sidebar { float:right; width:200px; }
div#sidebar ul { list-style-type:none; }
This makes it possible to partition my css files, so that it is easy to find the css-code that styles a particular tag, but if you introduce .right and other classes you are starting to disperse the rules into different areas of the css file, making the site more difficult to maintain.
I think the idea of having a very generic classes is born from the wish of making it possible to change the entire layout of the site by changing a couple of rules in a stylesheet, but I must say that in my 8 years of website development with 30+, different sites under my belt i haven't once changed the layout of a website and reused the HTML.
What I have done countless times is making small adjustments to regions of pages, either due to small changes in the design or to the introduction of new browsers. So I'm all for keeping my css divided into neat chunks that makes it easy to find the rules I am looking for, and not putting the code in different places to achieve a shorter stylesheet.
Regards
Jesper Hauge
Yeah, semantically speaking it is wrong, but, for example, there are times when I'm positioning images within a block of body copy and I'll give them the class "right".
Maybe "alt" is a more suitable class name.

Resources