Question

When using Yeoman to build an AngularJS project with Bootstrap, I see that in order to override some of bootstrap's CSS classes in the Yeoman-generated main.css file, I must use !important, otherwise the style from bootstrap.css is the one that wins and is applied. This seems weird to me - I think it would make sense that the "local" main.css file should be used for overriding styles and therefore it should "win".

For instance, I added the following at the top of the main.css file:

.navbar-text {
    color: red;
}

The relevant part in the index.html:

<!-- build:css styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<!-- endbower -->
<!-- endbuild -->
<!-- build:css({.tmp,app}) styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->

But it isn't applied because the style from bootstrap.css wins.

What would be the correct way to have my own CSS file which will always get higher priority over bootstrap.css? And why isn't it like that out-of-the-box with the yeoman/generator-angular?

Was it helpful?

Solution

You have to be strictly precise when you override a property.

Bootstrap declares .navbar-text class as being part of .navbar-default.
Excerpt of navbar.less code, imported by bootstrap.less:

// Default navbar
.navbar-default {
  background-color: @navbar-default-bg;
  border-color: @navbar-default-border;

  .navbar-brand {
    color: @navbar-default-brand-color;
    &:hover,
    &:focus {
      color: @navbar-default-brand-hover-color;
      background-color: @navbar-default-brand-hover-bg;
    }
  }

  .navbar-text {  //inside navbar-default
    color: @navbar-default-color;
  }

Therefore, you should override like this:

.navbar-default .navbar-text {
  color: red;
}

The following would NOT match:

.navbar-text {
    color: red;
}

Same applies when a property is specific for a specific media. You should override the property as being in the SAME media.

@media (min-width: 768px){
  .myClass {color: red}
}

would NOT be overriden by just:

.myClass{color: blue}

but by:

@media (min-width: 768px){
  .myClass {color: blue}
}

OTHER TIPS

I higly recommend this great article by css-tricks http://css-tricks.com/specifics-on-css-specificity/ on css selectors priority and order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top