Storing stylesheets for a website in MVC architecture - css

I am building up a website using MVC architecture. It takes a lot of css with it. I require atleast 20 css files to store within it each associated with some unique views. I want to know where can I store the css files? Either in a single root css directory or shall I store it with a particular view. Also linking these files within the common template file would be tedious enough. I mean it would show up 20 different tags. Is there any alternative way to do this? Please help. I am using codeigniter framework by the way.

What I do is store it all in a css folder inside the public folder (the one that houses your index.php file). I also have a helper method that generates the actual link tags, so in the template files, I just have something like:
<?= stylesheet('sheet1','sheet2','sheet3') ?>
The helper method that calls would then make the links (and assumes that they're in the public/css directory).
That cleans up the raw template files, though it does still make multiple tags in the files themselves. I use partial views, so there's a master view that has the main CSS file(s) that are used on every page (or almost every page), then add in on each template the ones that are unique to the view.
If you have 20 CSS files, you might want to go through and see what you can tidy up and make more generic. Any place where you have more than one of the same styles (even across files) is up for the chopping block. Any extra files should be relatively small and provide only overrides for the exception pages (and if you can genericize those more, so you use a file for more than one page, then that's even better).

I would recommend you to combine all the CSS files in a single file. Its easier to maintain and you will have only one request to the server. Having so many css files will only increase the loading time of your page. Also gzip the css files to increase the page speed.

Related

Is it good if I split my CSS file into multiple files for each page?

I'm Building a website, and It has a lot of pages approximately like 30 pages, and I linked these pages with one CSS file (the main css files) not to mention the other files such as bootstrap.min.css and other plugins that requires their own css files.
My point is that in all of these I'm using like the same css files, but in some pages I don't need all of the properties and styles in main.css file, so I'm thinking that I split that css file into multiple files, and create file called (global.css) and type in the properties that I'll need in all pages, and make another css file for each individual page.
My question is:-
Is it going to be helpful for the website speed if I split that main css into multiple css files and include only the necessary things for each page?
Ideally you want to abstracts your CSS files into many different SCSS files and then compiles them into one minified master file. One file for the header styling, one for links, one for typography. I was afraid of SCSS but now love it... Nothing changes in production, you are still running off CSS bit in development you are just making your life that little bit more organised.
NO,
you better dont want to do that if your code is small like less that 50kb or even 100kb
also if you provide seperate css for each page browser has to download each css file when user visit that page that will cost you one additional request for every single page this will slow down your page and affect your performace
instead I would suggest when your code goes live compress your code or minified it so youll get the more smaller version of your code
I also suggest to leverage browser caching (using .htaccess if you are using linux server)
above are the things which comes under front end performance improvement

Does CSS file sorting matter and if, why?

I have a website which uses 1 css file, it is called body.css and it consists of 841 lines. Should it be sorted in different files (header.css, footer.css page1.css, etc...), is it better in just 1 file or does it not matter?
The only thing I know for sure is sorting it in more files is a lot more readable.
Also if someone answers this I'd be most grateful for a little explanation.
My opinion would be one of two things.
1) If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests)
2) If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at runtime build time (runtime minification/combination is a resource pig).
With either option I would highly recommend caching on the client side in order to further reduce http requests.
So, there are good reasons in both cases...
A solution that would allow you to get the best of both ideas would be :
To develop using several small CSS files
i.e. easier to develop
To have a build process for your application, that "combines" those files into one
That build process could also minify that big file, btw
It obviously means that your application must have some
configuration stuff that allows it to swith from "multi-files mode" to "mono-file mode".
And to use, in production, only the big file i.e. Single CSS
Result : faster loading pages
maybe this will help you..
For optimal performance it is better to have only one css file.
But for readability it would be better to have different files for different parts.
Take a look at tools like SASS, which help do that without sacrifice performance. Additionally it has features to make your files even more readable by introducing variables, function and much more.
Using more files means more requests. It will take more time to load and make unnecessary requests to the server. I'd stay with one file.
The only good reason to have other css files would be if you have third-party components, to keep them separated and be able to update them easily.
The order matters: Rules loaded later will override rules with the same name loaded before (this is valid even for rules in the same file).
What do you mean that your website uses one CSS file? Normally you'd write your style definitions in multiple files, and they are concatenated (or not) into one file. My point is, what you are working on in your development environment should stay modular, readable, it shouldn't be influenced by what you have in production.
As for the order of the CSS files, yes, it matters, as you can overwrite your previous definitions.
For optimal caching I'd recommend you to build all the vendor CSS in one file, and your CSS in another file, versioned, so that if you change something in your code, only that file has to be updated by the browser.
But these things depend on the infrastructure. As the browsers are able now to send multiple requests simultaneously, having multiple files can lead to faster page load than only one. But I'm not sure about this.
you might want to take a look at gulp to automatically optimize, and minify your CSS code.
All css in one file is OK.
But it's free : you can make as many css file as you want.
However usually this is how it is:
1 global css file for the entire page. You put the common css in here that is useful for every page on your site. You can call it app.css or style.css or mywebsite.css or any name you want.
1 specific css file for a specific page when you want to specially separate this css from the global css file. Because it will contains css only useful for a few pages. For example you have a special component made by your own or a special functionnality. Example : you have made a spcial javascript code working with some html for uploading some file and you want to have your code js/css separate.
Usually, you can also have one css page for each page, but always one global css file for the entire site.
Note : Same question is also valid for javascript
Note 2 : You can also think about using a framework to minify your javascript and css into one single css / js file at the end. At work our technical boss use wro4j which works for java but it should exists many more other frameworks as you can search on google.

How does Drupal add module css files to the consolidated file when flushing my theme cache?

When I clear my theme registry Drupal runs off and builds out a nice consolidated css file, but it does this for different node/page types so that I get several instances of said file existing. I mentioned this in another question I asked (and answered), but my question is, how does Drupal deduce what css files it needs to add to the consolidated version? There must be numerous different places that control what modules appear on a particular node, so what constitutes a rule for another css file being built?
Well that wasn't an easy chain of functions to follow but I think I've got there...
Every time a page is 'refreshed' (i.e. built from scratch, not served from cache) all CSS files added with drupal_add_css() during that page build are aggregated and saved to a single file that is returned as the <link> tag for that page.
The following line in drupal_add_css() decides what the aggregated CSS file's name will be:
$filename = 'css_'. md5(serialize($types) . $query_string) .'.css';
$types in this context is an array of all of the CSS files added using drupal_add_css() during the current page build. The filename for the aggregated CSS contains a serialised string of $types, which essentially means that any other page that adds the same CSS files as that one will receive exactly the same file name and thus load the same CSS file.
So basically, the aggregation function is run for every single page build so all CSS added to that page will be aggregated every time. If certain pages happen to use the same modules then they will automatically be served the same CSS file as defined in the PHP snippet above. When you combine that with page caching you get the results you find in the HTML source on the different pages.
Hope that makes sense!

asp.net - Include CSS file only one

I'm stepping in to a project that has been going on for a few years.
One of the issues I saw immediately is that CSS files are being included in the master pages, the aspx pages, user controls and more, and also style sheets are created and imporeted via aspx files, and not linked. (A mess, I know)
It becomes impossible to debug styling issues.
What would be the best strategy for removing the double imports? Is there any built-in method to insure files are imported only once?
Thank you!
One way will be to have all CSS files embedded as resources then use Page.ClientScript.RegisterClientScriptResource.
Another way is leave the files as they are now and use Page.ClientScript.RegisterClientScriptBlock to include them after checking if already included by Page.ClientScript.IsClientScriptBlockRegistered giving it the unique key used in the Register method.
Either way, you'll have to remove the CSS includes from the .aspx itself and put it in the code behind.

CSS on a separate file or not?

Which is a better option: to store CSS on a separate file or on the same page?
Let's forget the fact that changing the CSS on a file makes it to apply all HTML pages directly. I am using dynamic languages to generate the whole output - so that does not matter.
A few things I can think of:
CSS on a separate file generates less bandwidth load.
CSS on a separate file needs another HTTP request.
On the other hand, if I compress the data transmission with Zlib, the CSS on the same page should not matter in terms of bandwidth, correct? So, I get one less HTTP request?
The main benefit of an external CSS file is that:
It can be used on multiple pages; and
It can be cached so it doesn't need to be loaded on every page.
So, if there is potential for reuse of the dynamically generated CSS between pages or on multiple views of the same page then an external file could add value.
There are several common patterns for dynamically generated CSS.
1. Generating a subset for a page
I've seen this occasionally. A developer decides to limit the amount of CSS per page by only sending what's necessary. I don't imagine this is the case for you but I'm mentioning it for completeness. This is a misguided effort at optimization. It's cheaper to send the whole lot and just cache it effectively.
2. User-selected theme
If the user selects a particular look for your site, that's what I'm talking about. This implies they might select a whole package of CSS and there might be a limited set to choose from. Usually this will be done by having one or more base CSS files and then oen or more theme CSS files. The best solution here is to send the right combination of external CSS files by dynamically generating the page header with the right <link> elements and then caching those files effectively.
3. User-rolled theme
This goes beyond (2) to where the user can select, say, colours, fonts and sizes to the point where you can't package those choices into a single theme bundle but you have to generate a set of CSS for that user. In this case you will probably still have some common CSS. Send that as an external CSS files (again, caching them effectively).
The dynamic content may be best on the page or you may still be able to make use of external files because there is no reason a <link> can't point to a script instead of a static file. For example:
<link rel="stylesheet" href="/css/custom.php?user=bob" type="text/css">
where the query string is generated dynamically by your header from who is logged in. That script will look up the user preferences and generate a dynamic CSS file. This can be cached effectively whereas putting it directly in the HTML file can't be (unless the whole HTML file can be cached effectively).
4. Rules-based CSS generation
I've written a reporting system before that took a lot of rules specified by either the user or a report writer and a custom report and generated a complete HTML page (based on the tables and/or charts they requested in the custom report definition) and styled them according to the rules. This truly was dynamic CSS. Thing is, there is potential for caching here too. The HTML page generates a dynamic link like this:
<link rel="stylesheet" href="/css/report.annual-sales.0001.css" type="text/css">
where 'annual-sales' is the report ID and 0001 is like a version. When the rules change you create a new version and each version for each report can be cached effectively.
Conclusion
So I can't say definitively whether external CSS files are appropriate or not to you but having seen and developed for each of the scenarios above I have a hard time believing that you can't get some form of caching out of your CSS at which point it should be external.
I've written about the issue of effective CSS in Supercharging CSS in PHP but the principles and techniques apply in any language, not just PHP.
You may also want to refer to the related question Multiple javascript/css files: best practices?
There is a method that both Google and Yahoo apply which benefit's from inline CSS. For the very first time visitors for the sake of fast loading, they embed CSS (and even JavaScript) in the HTML, and then in the background download the separate CSS and JS files for the next time.
Steve Souders (Yahoo!) writes the following:
[...] the best solution generally is
to deploy the JavaScript and CSS as
external files. The only exception
I’ve seen where inlining is preferable
is with home pages, such as Yahoo!'s
front page (http://www.yahoo.com) and
My Yahoo! (http://my.yahoo.com). Home
pages that have few (perhaps only one)
page view per session may find that
inlining JavaScript and CSS results in
faster end-user response times.
If you're generating HTML dynamically (say, from templates), embedding CSS allows you the opportunity to also generate the CSS dynamically using the same context (data, program state) as you have when you're producing the HTML, rather than having to set that same context up again on a subsequent request to generate the CSS.
For example, consider a page that uses one of several hundred images for a background, depending on some state that's expensive to compute. You could
List all of the several hundred images in rules in a seperate, static CSS file, then generate a corresponding class name in your dynamic HTML, or
Generate the HTML with a single class name, then on a subsequent request generate CSS with a rule for that name that uses the desired image, or
Do (2), but generate the CSS embedded in the HTML in a single request
(1) avoids redoing the expensive state computation, but takes a larger hit on traffic (more packets to move a much larger CSS file). (2) Does the state calculation twice, but serves up a smaller CSS file. Only (3) does the state calculation once and serves the result in a single HTTP request.
Browsers can cache the CSS files (unless it changes a lot). The bandwidth should not change, because the information is sent, no matter where you put it.
So unless the css quite static, putting it in the page costs less time to get.
I always use mix of both.
site-wide styles are in separate file (minified & gzipped),
any page-specific styles are put in <style> (I've set up my page templates to make it easy to insert bits of CSS in <head> easily at any time).
Yes and no. Use a .css file for most rules; your site should have a consistent look anyway. For rare, special case, or dynamically generated rules you can use inline 'style=""'. Anything that sticks should move into the .css, if only to make transcluding, mash-ups, etc. easier.
Keep it separate. HTML for centent, CSS for style, JavaScript for logic.

Resources