How can I override Bootstrap CSS styles?

前端 未结 12 1344
囚心锁ツ
囚心锁ツ 2020-11-22 05:35

I need to modify bootstrap.css to fit my website. I feel it\'s better to create a separate custom.css file instead of modifying bootstrap.css

12条回答
  •  佛祖请我去吃肉
    2020-11-22 06:06

    Using !important is not a good option, as you will most likely want to override your own styles in the future. That leaves us with CSS priorities.

    Basically, every selector has its own numerical 'weight':

    • 100 points for IDs
    • 10 points for classes and pseudo-classes
    • 1 point for tag selectors and pseudo-elements
    • Note: If the element has inline styling that automatically wins (1000 points)

    Among two selector styles browser will always choose the one with more weight. Order of your stylesheets only matters when priorities are even - that's why it is not easy to override Bootstrap.

    Your option is to inspect Bootstrap sources, find out how exactly some specific style is defined, and copy that selector so your element has equal priority. But we kinda loose all Bootstrap sweetness in the process.

    The easiest way to overcome this is to assign additional arbitrary ID to one of the root elements on your page, like this:

    This way, you can just prefix any CSS selector with your ID, instantly adding 100 points of weight to the element, and overriding Bootstrap definitions:

    /* Example selector defined in Bootstrap */
    .jumbotron h1 { /* 10+1=11 priority scores */
      line-height: 1;
      color: inherit;
    }
    
    /* Your initial take at styling */
    h1 { /* 1 priority score, not enough to override Bootstrap jumbotron definition */
      line-height: 1;
      color: inherit;
    }
    
    /* New way of prioritization */
    #bootstrap-overrides h1 { /* 100+1=101 priority score, yay! */
      line-height: 1;
      color: inherit;
    }
    

提交回复
热议问题