Overwriting CSS Vs Selectively loading CSS with Modernizer (YepNope) - css

Unsure how to test this but are there any performance gains from loading in a CSS stylesheet via a query with Modernizer.load as oppose to just overwriting the rule with a CSS classname in the same stylesheet.
For example, if a device has touch support then I have a different layout to load, is it faster to do...
{
test: Modernizr.touch,
yep : 'css/touch.css',
nope: 'css/base.css'
}
Or overwrite the styles in the same stylesheet...
.container { width: 50% }
.touch .container { width: 100% }
Seems the difference comes down to the speed of the extra query Vs the weight of having one big CSS file?

you need to understand you have 3 details here.
the call to the server.
the browser time to calculate all your parent style's
the weight of the files.
so the answer is.
if you write the css without the line break's between the property the 1 big file will be more big from the 2 files. and is answer to the weight cause 1 file is better.
if you have whole page to make with .touch class is more calculate to came the file with the classes.
so, what i'm do is to call to server just one time and make one file cause is better to load all style's together and the call to server (the important time value) will be shortly

I think both options are perfectly valid.
If there's a large amount of CSS code specific to touch, then I would say yes, pull them in with Modernizr to avoid the extra burden on non-touch browsers.
However, my preference would be to generally use override styles for this kind of thing.
The reason for this is that with the Modernizr option, you'll be delaying the loading of the touch styles, because it can't do the Modernizr test until the Modernizr script is loaded and ready to run.
So in comparison to being loaded as part of the main page load and being ready for the initial rendering, it is only loaded after page load, and may not be ready straight away.
The result of this could be that the page may be loaded and displayed before the touch styles are loaded. Not ideal.
This isn't to knock Modernizr -- it's a great tool -- but if you can do what you need to without using it, it's generally better.

Related

To put or not to put styles in css file?

I have a few lines of styles in every page. I'd rather not to put them in one css file for it might affect the styles of other page.
Do we really need to put the styles on a css file or is it ok to have
<style>...</style>
on every page?
What are the advantages of putting the styles in one page regarding to it's speed?
Does it speed up the loading of a page?
Basically it is a compromise option. Like Marty Wallace and Marc B stated.
The speed aspect is therefore a consequence of the option you take, as they are both valid. Just remember these two factors:
should you choose to use the CSS in the <style> section of your HTML file, it will be loaded everytime with each page load. Therefore, the more CSS rules you have in this section, the bigger the file, hence, longer loading time and slower speed.
If you <link> a stylesheet, that file will be requested everytime you load the page as well. So more or less the same relation to loading time is implied, although it may differ a lot in absolute value.
Also, you should have in mind that most browsers have caching mechanisms to optimize the usage of CSS. Try to read more about it so you can take advantage of it as well.
My opinion is that a mixed approach is probably the best option. Choose the rules that are to be applied to the common elements between your different pages and put them in a linked CSS file. Then, use the <style> tag to set specific CSS for elements on that page. This is my I-don't-care-about-it-that-much way of doing it.
Most of the time I found that CSS doesn't impact performance that much - but of course, it depends a lot on how much CSS you are actually using.

Do unused CSS styles affect load times

I am wondering if unused CSS styles affect load times because I normally break my sections of my code using this format
/*===================
Nav-Styles
===================*/
However, I also use coda to write my code. It has a code navigator, which detects ids followed by {}
what I thought might help with my code organisation is to create this format of break
/*==========================================
#----NAV-STYLES-BEGIN {} /* Nav Styles */
==========================================*/
This will mean my section breaks will them appear in the code navigator and can be jumped to quickly. However, if this is going to cause speed related issues, the means will outweigh the end.
Is this a bad idea or will the difference be so insignificant that it's worth doing if I wanted?
The answers here are not correct.
Unused CSS does two things:
Adds more bytes that need to be downloaded before the engine can start rendering the page
The browser engine has to go through each css selector to evaluate whether it is on the page and how it should render.
The second part is crucial. If 50% of your css file is unused css, you are essentially have the browser engine take twice as long to render your CSS for the page. Of course, the type of CSS selectors you have matter as well, so the twice as long is more of a easy example than full truth. Never the less, unused CSS increases your browsers page load time, even when the file is cached on the local drive.
Any unused CSS or JS that is passed over the wire to the client will hurt the sites performance at the least to a small degree. The unused CSS increases the size of the page, therefore increasing the time it takes to download a page. A few characters here and there will not have a huge impact on your download times, however if there is a large amount of unused styling there may be an impact. This is why many people compress their CSS and JS.
The effect of this is going to be unnoticeable, and could be described as negligible at best. Regardless, you could use a build script to remove all comments and minify your CSS. This will improve load times, if only slightly.
The short answer - go for whatever is easiest to develop with. You can worry about production later.
I hesitate to add

How to remove unused styles from twitter bootstrap?

My bootstrap stylesheet size is around 120kb.
But I'm only using 25% of that stylesheet code.
I don't want that span* class. I tried it by customizing it in bootstrap customize page.
I unchecked grid system, But I still see span1 - span12 class in forms, tables and responsive layouts.
Can someone help me to remove those codes?
After an hour of struggling with grunt, I decided to try uncss by itself, and it was much simpler. If you only have a few pages to do, or don't mind doing it manually, I'd recommend doing that.
The uncss page has full instructions, but to summarize:
Have node.js installed.
npm install -g uncss
Copy the sample file from the uncss page and name it anything with a .js extension. I named it uncss.js.
Replace the files array with your html files. (It looks like var files = ['my', 'array', 'of', 'HTML', 'files'])
Replace the stylesheets array with your stylesheets. (It looks like stylesheets : ['lib/bootstrap/dist/css/bootstrap.css', 'src/public/css/main.css']). Likewise change the value of "csspath" if you need to.
Run node uncss.js (or whatever you called your uncss file).
It spits out the optimized CSS straight to the command line, so save it to a file with something like node uncss.js > mynewcss.css.
There are a bunch of options to tailor the behavior. I ignored all of them and it worked fine, but they're there if you want them. The page I tested it on went from 138kb to 9kb.
I got exactly the same problem!
I wrote a tool to remove all un-used css style rules in bootstrap.css
As a result, 59% rule has been removed, css file size reduced from 121KB to 59KB and increased about 5 score when testing with Google PageSpeed
The source code is here css-optimizer
Are you more concerned about the impact of the file size on the loading time for your users? Or want to make it easier for you to read/understand the CSS if it's shorter?
Either way, I suggest you don't spend too much time worrying about removing every single extra CSS style. Uncheck the elements of Bootstrap that you don't plan on using and download the customized version. For the live/production version of your site, use a minimized version of the CSS which will further reduce the file size.
If you just want to keep the code more simple for your use, that's definitely understandable but the Bootstrap team has done a great job of organizing it. Spend a little time with it.
Consider that trying to completely remove all span* references will remove functionality that you might use like controlling the width of form fields. These can be very useful, even if you're not using the grid.
I assume that twitter bootstrap heavily relies on those span* classes. When I only toggle the "table" checkbox under "Base CSS", I still get span* classes in the compiled css, because they are rendered anyway. Take a look at https://github.com/twitter/bootstrap/blob/master/less/tables.less:
// R.185: Change the column widths to account for td/th padding
.table td,
.table th {
&.span1 { .tableColumns(1); }
&.span2 { .tableColumns(2); }
&.span3 { .tableColumns(3); }
&.span4 { .tableColumns(4); }
&.span5 { .tableColumns(5); }
&.span6 { .tableColumns(6); }
&.span7 { .tableColumns(7); }
&.span8 { .tableColumns(8); }
&.span9 { .tableColumns(9); }
&.span10 { .tableColumns(10); }
&.span11 { .tableColumns(11); }
&.span12 { .tableColumns(12); }
}
So I'm afraid you should cannot remove them with the customizer, only manually.
I have a template using Bootstrap 2, which is the required system for Joomla. I just did this manually and found it easy to do. The Bootstrap CSS file is very nicely constructed and well ordered in sections. I removed the entire contents of the file to bootstrap_unused.css and then also copied that to bootstrap_original.css.
I then cut out from bootstrap_unused.css what I knew was in use, being careful to preserve the order, and pasted it back in. Most of it worked first time and reduced the file size from 144KB to 14KB. I then needed to add some bits and pieces back in for forms etc. and ended up at 30KB.
If I need any other features in the future, I can pull them back in from bootstrap_unused.css and I always have bootstrap_original.css for reference.

Inline styles vs styles in CSS

I know placing all your styles in a CSS file is the best thing to do as it is a lot neater.
But does it REALLY matter if the styles are inline or in a CSS?????
Edit below
My plan is to just place the styles in my MasterPage and all other pages will use the MasterPage....I believe the correct term is not "INLINE" but Embedded???
Some thoughts from one with experience, rather than a 'purist':
Storing all styles, for a large application, in one CSS file is not maintainable. You'll have perform a text search of the file to find the style you're looking for, or scroll a lot, and there's a higher chance that you'll overlook related styles when making an update.
If certain styles are particular to a page, not globally used, it is more maintainable to keep them in a style tag within the head tag.
Deep CSS inheritance hierarchies are also not maintainable. These are much, much worse than inline styles!
The CSS language itself does a poor job of applying styles to many elements in more complex structures. Consider lesscss, sass, or even jQuery for more than basic application of styles.
Lots of developers use HTML for presentation, mostly DIVs, when they think they are doing the right thing, or lecturing others. Some example above!
Using Inline CSS:
Repeat the same rule for every
element in the page.
More code and bigger file size to
transfer to the client.
Harder to maintain, suppose you want
to change the width to 200px, you
will need to go through all the page
and edit one by one.
inline:
<div style="width:100px; height:100px;"></div>
<div style="width:100px; height:100px;"></div>
external OR put css classes in the head [embedded styling]:
<div class="big"></div>
<div class="big"></div>
Based on your edit: that seems not to be inline CSS as in my example above, it is the same idea as using an external file, so if you want to do that go ahead, it is the same.
It matters because your code becomes very difficult to maintain or update if you use inline styles. Keeping your styles in style tags or separate CSS files allows you to comply with Don't Repeat Yourself, which is probably the most important development principle.
That being said, if you are absolutely certain that a piece of styling is unique to a given element, and also that it won't ever need to be tweaked, you can feel free to use inline styling. I sometimes use inline style for throwaway code and for things like landing pages (once they're done, they're done).
No but it is alot easier to make changes to the css if you only have to look one place instead of all your headers/inline
One other thing, your markup looks alot cleaner if you dont have eny css/javascript inline
When creating master pages I use in-line styles to create the basic layout of the page. For instance I include all of the styles that position the header at the top of the page, main content in the middle and footer at the bottom. Pretty much every style attribute related to positioning, I include in the masterpage as an inline style.
Storing styles in one document helps you to control on your entire project. Furthermore less code to maintain and applying changes.
It is a loth easier for maintenance... does it really matter depends on what you think what is important... why wouldn't you use a css file?
Do you mean putting your styles in the with or attaching them as 'style="x"' to your element?
There's several reasons for avoinding inline CSS.
1) Maintenance, it's easier to make changes to a code where all css is seperated from the markup itself. It also makes the code more readable as avoiding alot of inline css gives you less code.
<div class='test'></div>
is easier on the eye than:
<div style='background:yellow;width:10000px;height:10px;position:absolute;top:10003px;left:132032px;'></div>
When the css is inline you will also have a hard time finding where the code itself is and comparing styles. You will also often end up repeating the same code several times because you can't use classes.
2) Performance, CSS files can be gzipped, making for a smaller load. It's also easier for the browser to handle when it get js and css served as files.
3) Keeping with the best practice. Some other poor developer might want to edit your code later, and he sure would be happy if you kept away from inline CSS.
Now of course you can do CSS in the head of a document too, but why make your files bigger than they need to be? More code into the same file makes for more mess. And you can't gzip it if you do.
#Etienne , there is one disadvantage doing this way , if you want to deploy any changes to production you have make a build and push it.
If you maintain everything as css , you can just push the css file changes and invalidate the load balancer cache.
I thought this is a good point to mention.
When it is best to use inline style
Inline style is the best solution in situations when some style is created dynamically from user input via server-side code (ex, WordPress plugin), to be applied only to a single HTML element, in such cases insert it into an external CSS file causes only problems:
There is the need for a server-side code that creates a CSS class
with the dynamic style inside it.
There is the need for a server-side
code that write and save the .css file
There is the need for a
server-side code that is able to link the CSS classes created to the
correct HTML elements You must load an external CSS file for no
reason, this is a downgrade of performance (file size and 1 more HTTP
request)
In many cases, where the dynamic codes are just one or two,
the problems are startling clears: you must create a file of ex.
800bytes with 2 lines of code, and load it as external files.
Greater exposure to bugs. More a code is complex more are chances of bugs. The server-side codes above are very complex in comparison to the simplicity of the task they do.
Real use-case:
Imagine a scenario where a user wants to upload an image and use it as a background in an HTML element. With old rule is just style="background-image:URL()". with the new rule some code must create and save an external file, with just the code style="background-image:URL()", create a CSS class for it, write it in the HTML component, load this CSS file with just one line of code. Totally nonsense. Consider also that this operation must be done every time the user updates the image.
Final result:
Worst performance due to 1 more HTTP request and large, complex, server-side codes.
Wasting hours of time for authors to develop something that is not only useless but also creates real problems.
At least one more file in the project
Worst readability/comprehensibility of the code because a user must check the HTML and then find the CSS code of the linked CSS class to see the value of the style.
When it is best to use an external CSS file
In all other cases than the ones explained above, in short, when the style is fixed and never change you should put it in an external CSS file.

What is a good CSS strategy? [closed]

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
We have a large ASP.Net website that has a single css stylesheet which is getting out of control.
I am thinking of using the following strategy (taken from http://www.techrepublic.com/article/developing-a-css-strategy/5437796/) which seems logical to me...
you might have one CSS file devoted to sitewide styles and separate CSS files for identifiable subsets of site pages (such as pages for a specific department or pages with a different layout style). For styles that are unique to a specific page, use a separate CSS file for each page (if there are too many styles to fit comfortably in the document header). You link or import the appropriate CSS files for each page, so that you load all the styles needed to display that page, but very few unnecessary styles that only appear on other pages.
Is this a good way to proceed? What are the alternatives?
I think the best option is to divide css in:
-layout.css
-content.css
Then if you need other more specific you can add more like an css for the ads: ads.css, or one css for a specific section.
I would also add ie.css for IE css hacks.
I would not speak about creating one css for only one page: the problem you can have if you use too many css, is that your page will have to do more requests to the server and this will slow your page.
This is why i recommend you to implement an HttpHandler which will create a cache copy in only one file of the css you need at the moment. Look here:
http://blog.madskristensen.dk/post/Combine-multiple-stylesheets-at-runtime.aspx
There are three principle methods used for breaking up stylesheets: property-based, structure-based, and hybrid. Which method you choose should most be based on workflow and personal preference.
Property-Based
The most basic, representative form of a property-based breakup would be to use two stylesheets: structure.css and style.css. The structure.css file would contain rules that only used properties like height, width, margin, padding, float, position, etc. This would effectively contain the "building blocks" necessary to arrange the elements of the page the way you want. The style.css file would contain rules with properties like background, font, color, text-decoration, etc. This effectively acts as a skin for the structure created in the other stylesheet.
Additional separation might include using a typography.css file, where you'd place all of your font properties. Or a colors.css file, where you'd place all of your color and background properties. Try not to go overboard because this method quickly becomes more trouble than it's worth.
Structure-Based
The structure-based method of breaking up stylesheets revolves around segregating rules based on what elements to which they apply. For example, you might see a masthead.css file for everything in the header, a body.css file for everything in the content area of the page, a sidebar.css file for everything in the sidebar, and a footer.css file for everything at the bottom of the page.
This method really helps when you have a site with lots of distinct sections on each page. It also helps minimize the number of rules found in each stylesheet. Unlike the property-based method, which tends to have a rule in each stylesheet for each element on the page, with this method you only have one rule in one stylesheet for any given element.
Hybrid
As you might expect, the hybrid method combines the best of both methods and it's my preferred choice. Here you create a structure.css file, just like in the property-based method, using only those properties that you need to create the basic layout. Then you create additional stylesheets like masthead.css, which skins the header; body.css, which skins the content; etc.
Other Considerations
One problem that plagues each of these methods is that by creating multiple stylesheets, you require that the client's browser fetches many files. This can have a negative effect on the user experience because most browsers will only make two concurrent requests to the same server. If you have seven stylesheets, that means adding potentially hundreds of milliseconds on the initial page load (this effect is lessened once the stylesheets have been cached, but you want to make a good first impression on those new visitors). It's for this reason that the CSS sprites technique was created. Breaking up your stylesheets may wipe out any gains made by using sprites.
The way around this is to compress your broken-up stylesheets back into one stylesheet when the user makes a page request.
To get the best of both worlds, consider using a CSS meta-language like Sass. This allows a CSS author to break one stylesheet into many while still only presenting one stylesheet to the browser. This adds a step to the CSS authoring workflow (though it could potentially be scripted to compile the Sass into CSS any time a Sass file is updated), but it can be worthwhile, especially when considering some of Sass' many other benefits.
What you can do is have lots of easy to manage, separate files for development, then smoosh them all together into one file and minify it on your live site.
This is a little more work to set up, but gives you the best of both worlds - easy to manage site + fast page loads.
Edit: Yahoo's YUI compressor seems to be the best minifier around. It can compress both CSS and Javascript.
My solution, amidst plenty:
base.css / reset.css: your foundation {base layout, type, color} -- 100% reusability
helper.css: basic layout rules for modules as well as 'utility classes' {grid variations, forms, tables, etc} -- 90+% reusability
module.css: complex layout rules for modules {semantic modules like .post or .comment} - 75% reusability
layout.css: template-based rules {#hd, #bd, #ft, #homePage, etc.}- almost no reusability
color.css: all color rules, combined - 50% reusability
type.css: all type rules, combined - 75% reusability (text styling has less variations)
this separation also allows mobile and print versions for the layout sheets, all controlled by #import via the stylesheet I link to the html.
I am using this for a medium-sized site. For extra organization, I keep each sheet sectioned basically the same {wrapper, general, unique, etc}. I also tag my selectors and properties, as well as indent them in order of dependency inside the same selector group, so I know what rules I am referencing or extending. This framework allows nearly infinite expansion while keeping things organized, understandable, and reusable. I've had to refactor a 7000+ line master.css file a month ago, so this is a new system I am trying out. I've found that 100% content-semantic CSS isn't as scalable and easy to understand as a semantic/layout hybrid, since that's what CSS is used for anyway.
1.25-yr-later-edit: Another method which might be more relevant is to just use a good CSS text editor. I'm positive VS is crap for working with CSS, unless you happen upon some extensions. If you're on windows, give E Text Editor a shot, b/c it's a TextMate Windows port and has bundles designed for CSS and markup that give you much better syntax highlighting and autocompletion. What you then can do is organize, even a 8000-line stylesheet, into collapsible folds:
/** Start Module 1 */
[css]
/* End Module 1 **/
And use the symbol list to display for you a quick TOC on the fly with a query like Start or Module 1 It also indexes lines with /** these types of comments **/ (great for tagging areas) and all CSS selector chains. You should have no trouble working with single big files with E. Besides, unless you're progressively enhancing your CSS it's all going to get minified anyway. I would also make sure to indent your CSS to somewhat mimic the structure of DOM section it is referring to.
.container {}
.container .inner {}
.container .head {}
.container .inner.alt {}
Otherwise, I agree with the '1 Base CSS and 1 Page/Section CSS` method, though it entirely depends on your business requirements.
I would check out YUI CSS. Maybe not the answer you were looking for, but YUI CSS removes much of the hassle with different browsers etc...
Work out some simple rules that work for you (or your company).
Divide your CSS into separate files, such as:
layout.css
content.css
menu.css
typography.css
Decide what declarations will go in each file, for example, ensure:
font-weight, text-decoration, font-family
and
h1, h2, h3, h4, h5, h6, a, p, li
All reside in the typography CSS file. Decide what to do for edge cases, such as border properties on headers, padding and margins on text elemants (layout or typography).
If your sets of declarations are getting unwieldy, some people like to organise them alphabetically.
Indent your css, for example:
#logo h1 {text-indent: -9999px}
#logo h1 a {display: block; width: 200px; height: 98px; backround...}
Comment your CSS, including references to other files if other rule for that specific selector reside there.
If you do divide you CSS into separate files, consider consolidating and compressing them into one file as part of your build & deployment process.
Make sure every developer is well aware of your standard for CSS.
Also, somewhat relevant, I've just been made aware of a Firefox plugin for finding unnecessary selectors. It's called Dust-Me Selectors.
netadictos makes some good points and I would concur. It's easy to seek reasons for more Css but the benefits of keeping them lean are far greater in the longer term.
In addition, have you looked at using themes and skin files within asp.net? The combination of .css and .skin can dramatically reduce the overall size of your Css, which is marginally good for performance but very good for easier administration.
Some exceptions could be contained within the one css file but if things are radically different within the one then you may consider a separate css or even a separate site if they are that different. Obviously you might load different versions of the themes depending on which user it is. This is where you could have an explosion of Css files. That is, say you had a css for each page and then you wanted to have different for different clients on your site, then you'd be growing exponentially. This of course assumes you have this challenge.
I wonder the same thing with regards to JavaScript files. If your site is highly dependent on Ajax to the point where almost every page requires some kind of custom Javascript then were do you stick it all?
Best practices oftern spout not having javascript in the page but as external files (as with css). But if you have a .js file per page then things will slowly get out of hand.
I'm not sure about Windows equivalents, but on the Mac you can get CSSEdit, which allows you to add folders to CSS files and manage them like that. There's a good explanation of it in this article.
Global css files have caused me headaches before. CSS usually isn't namespaced, so if two different modules create a div with a class of "box", then the intent of one overwrites the other. Also, styles on the [a] tag, [p] tag and other basic tags (ie. styles not based on classes or id's) will wreck havoc on 3rd party controls as your global style sheet cascades onto an html component that was designed assuming no other css on the page. Inappropriate usage of text centering to center elements can lead to hard to debug global centering. So I favor multiple css files. I've seen css managers (http modules that merge css together at request time), but decided the extra http requests is well worth limiting the scope of the damage ill considered css can do to my application.
We use Ruby on Rails so we have a clear controller/action pair, we use this to reference both CSS classes and Javascript views.
Specifically, grab the name of the controller+action name and embed this as a ID in the view, put it on the body tag or your main content div.
<body id="users_list_body">
Where "users" is the name of the controller, "list" is the action. Then in your CSS you have rules likes
#users_list_body
So you can scope all of your specific CSS to that view. Of course, you also have more general CSS to handle overall styling. But having this ID defined more easily allows you to create specific CSS for individual pages (since a controller/action maps to a specific page).
You end up having rules like this
#users_list_body table
#users_list_body table thead
Do the same for Javascript. So in the footer of every page you take your same controller/action name pair and embed it in a function call
//javascript
if(V.views.users_list) { V.views.user_list(); }
Then in your external Javascript you have something like
V = {};
V.views = {};
V.views.user_list = function() {
//any code you want to run for the Users controller / List action..
//jQuery or something
$('#save_button').click({ ... });
}
with all of your Javascript code scoped to a specific function, it ends up being all encapsulated. You can then combine all of your Javascript files into one, compress it and then serve it up as one file and none of your logic will conflict. One page's JS will not conflict with any other page's JS because each page is scoped by its method name.
Whatever your choice is, avoid using the #import directive.
Makes the browser load stylesheets sequentially, hence slowing down loading and rendering for your page.
Here is what I do: I keep my stylesheets separate, somewhat along the lines of what others have suggested. However, I have a script that concatenates them together, minifies them, adds the headers, and then gzips them. The resulting file is then used as the stylesheet and if it goes beyond the expiration date, it automatically recompiles. I do this on a sitewide basis for all the common files and then also on a page specific basis for CSS that will only appear on that page. At the most, I will only ever have 2 CSS files called per page and they will be compressed, which minimizes download time and size and the number of page requests, but I will still have the benefit of separating them in whatever way makes sense to me. The same strategy can also be used for JavaScript.

Resources