Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of overriding CSS

I'm currently working with Bootstrap and for my site I want to override certain default settings it comes with. A lot of Bootstrap rules are quite deeply nested and thus most often than not take priority over whatever I might define.

In my overrides css file, do I have a better option than to slap

!important

on each rule, or is that how everybody's handling it these days?

like image 746
Alexandr Kurilin Avatar asked Feb 21 '13 21:02

Alexandr Kurilin


1 Answers

FWIW, this works for me.

  • If you aren't already using LESS, take some time to figure it out, it will save you heaps of time and makes it easy to keep everything organised http://lesscss.org. You will be well rewarded ;)

  • Instead of editing the original Bootstrap LESS files and losing everything on the next Bootstrap update, create a new theme-css.less file and perhaps a theme.variables.less file and save them in the same directory as your Bootstrap LESS files

  • Edit bootstrap.less so that your new files are compiled correctly,

    ..

    // CSS Reset @import "reset.less";
    // Core variables and mixins

    @import "variables.less"; // Modify this for custom colors, font-sizes, etc
    @import "mixins.less";

    @import "theme-variables.less"; // <==== Your custom CSS variables

    // Grid system and page structure
    @import "scaffolding.less";
    @import "grid.less";
    @import "layouts.less";

    // Base CSS
    @import "type.less";
    @import "code.less";
    @import "forms.less";
    @import "tables.less";

    @import "theme-css.less"; // <==== Your custom CSS

    ..

  • Use the Bootstrap customise page to located the names of the variables that govern much of the the CSS which you may wish to customise. Change these as req'd and add to your theme.variables.less file

  • Use the LESS nested rules as per http://lesscss.org/ . <== this is important. It hugely simplifies what would otherwise be complex CSS

If you are new to LESS I realise that this isn't a simple 5 minute fix, but once you get it setup and start using the nested rules your CSS will be beautifully simple and easy to maintain.

UPDATE Jun 2015
The above technique is a bit dated now. Still works but Jake suggested a change which I like and it simplifies long-term maintenance.

Instead of editing the main bootstrap.less file:

  • create a new theme.less file

  • import bootrap.less and your custom changes, e.g.:

    @import "path-to/bootstrap.less;
    @import "path-to/custom.less;

  • compile theme.less

Doing it this way means there's less chance that your custom changes could be lost if you update your bootstrap.less file

like image 165
David Taiaroa Avatar answered Sep 28 '22 04:09

David Taiaroa