How to remove unused styles from twitter bootstrap? - css

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.

Related

anomaly when overriding bootstrap in django

For the past two hours I've been trying to figure out a strange behavior when trying to override bootstrap in Django.
At the beginning, without any custom css file, the result was this:
Then I created a custom css file: my_site/css/master.css
.index-jumbotron {
background-color: #006DB0;
}
#main-title {
text-align: center;
color: white;
}
It resulted in this:
So far, so good.
But now, if I change anything on that same file (even when putting !important and taking good care of the specificity system), the result is always the same as the image immediately above.
However, when I indicate my template to point to another file my_site/css/master2.css or css/master.css, indeed the result is as I would have expected:
I can't get my head around this. Do you have any idea? Do you know if the package django-bootstrap3 could have anything to do with that? I installed it in between my two different version of the custom css file.
Looks like a browser caching issue - did you say 'disable cache' in the developer toolbar (network tab) of your browser? This is usually the easiest solution.
Another option is to open the styles file in your browser and hit 'ctrl+r' to force reload of the css file.

How to avoid form-control in all inputs with Twitter Bootstrap 3?

I am building a website with a framework in which the HTML is automatically generated. Twitter Bootstrap 3 needs the class "form-control" added to each input to properly apply the width to such inputs. Problem is that to add that css class from code, I would need to change the framework in many places.
Is there a work around? Maybe some javascript/jquery that searches all labels in my form, for each label it finds the associated input and finally add the css class? But I really don't know how to do it.
Thanks in advance for any help.
You could edit forms.less and recompile the css, but it could be tricky because you don't want all inputs or text areas to have that .form-control styling.
If you have an ID for your form that you want to apply it to, this should help:
$('#yourFormId input, #yourFormId textarea, #yourFormId input, #yourFormId select').addClass('form-control');
You would need to make sure you are adding all the form field types that are in your form, but that above line would probably cover most of them. This is pretty hacky though, depending on your framework there may be some sort of mixin or function to include class names in auto generated forms.
This is a bad idea because it is a "hacky" implementation of bootstrap. Not only do you need the classes you need the proper html structure. The amount of time trying to craft some magic javascript to implement these two changes would be better spent modifying the framework.
A solution could be to use Bootstrap's Less classes instead of the compiled library and somehow add the necessary tags in your code.
Take a look at this article.
I've not faced this specific problem, but in general when working with Bootstrap 3 I'll build the .less files myself with my own specific changes, e.g. in my .less file:
/* Import the Bootstrap 3 .less files */
#import url('../../Bootstrap/less/bootstrap.less');
/* Now implement my own styling below */
Working with .less, you might be able to pull in the relevant styles from the relevant part of the framework, something like this (where .mydiv is your container element) :
.mydiv {
input,
select,
textarea {
.form-control;
}
}
This would pull in the .form-control styles and apply them to input, select and textarea elements inside .mydiv. I've not tried this, but it's worth a try!

Overwriting CSS Vs Selectively loading CSS with Modernizer (YepNope)

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.

Managing CSS conflicts

So i am working with a few CSS developers and every now and then we run into layout issues which have been fixed previously because one of the css developer did something which conflicted with something else.
We are already using SVN .. each CSS guy has his own css file he works with. So my question is what steps should be taken to minimize:
1 : layout conflicts
2 : increasing re-usability of previously written styles.
3 : minimize wasted time trying to merge the styles together in the final css.
I would really appreciate any tips you guys have to offer.
Update:
I am not one of the CSS developer, i just take care of the backend stuff.. so please keep in mind that i am a total newbie when it comes to CSS norms.
Define a naming convention for your CSS files to prevent conflicts (prefix?)
Have an automated process that you can run before check-in (check-in tests) to see any potential conflicts
Discuss what you will add (code review?) and avoid the conflicts altogether
I dont know of any namespacing you can do to avoid CSS stylesheet name conflicts so, I suggest those. They are things that many large companies do already.
A good starting point is to disallow using general tags in specific css files. Each developer should only use classes and ids. All general tags should be included first on all pages, so that special tags may overwrite them later.
Changing the general tags should require more planning than changing each developer file.
With general tags I mean
div {
/* affects all divs */
}
and each developer should only do
div.something {
/* potentially overwrite defaults for div */
}
and the html file should be like
link href="general.css"
link href="dev1.css"
link href="dev2.css"
The best thing you can do is assign areas of responsibility - if you are all working in the same area of the site you are bound to have conflicting changes and will only create difficulties for yourselves because you will constantly be stepping on each other's toes.
Once you have established a common baseline for the styles of your site, divide the main areas of the site amongst you and only work in those areas. When changes need to be made to the baseline, make them out in the open and communicate with your teammates about this change so that no one is surprised.
I am not going to pretend that this is easy to do - working on something as a team is a challenge that the entire software development industry has yet to completely solve. Good luck!
All others have good answers, but I'll add this: Strongly encourage the use of IDs in selectors. ID-ing important elements generally pays off in the long run because it allows for better testability and less conflicts.
CSS Example:
#myid selector { ... }
#myotherid selector { ... }
General styles really should go in a top-level or general stylesheet that everyone manages, if possible.

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