Twitter bootstrap override `a` in `navbar`

2020-03-26 12:10发布


How to ovveride padding on a in navbar

I got the following as css rules for

.navbar .nav > li > a {
  float: none;
  padding: 10px 15px 10px;
  color: #555555;
  text-decoration: none;
  text-shadow: 0 1px 0 #ffffff;

and I would like to have padding: 5px, 5px, 5px


And there is the problem with using bootstrap, its nice until you have to modify it.

I found your particular rule by going into bootstrap.css and searching for ".navbar .nav" (I also use bootstrap in a ruby on rails project) it was around line 4380. (this is for the un-minified version)

So you have several options:

  • You can find it and modify the rule there.

  • You can override it inline if you just need it on a few.

  • You can put it in a css file you know (I am assuming your using rails) rails will pre-compile it to be later then twitters rule (in css the last rule read is the one applied).

  • Or you could write your own rule and use !important at the end of the rule. That would look like this:

    .navbar .nav > li > a {
        padding: 5px 5px 5px !important;

Which is dangerous, (it can make it harder to maintain your css in the long run.) But still a valid option if all else fails.

As a note: You should actually be using the un-minified version of bootstrap for development. When rails compiles your assets for deployment, it will minify it for you. Makes modifying 3rd party files 100x easier to work with.

(This also assumes your not using a bootstrap gem to import your css, in which case see one of the options above)


To 'override' a style we need a more specific rule. The accepted answer uses the !important rule, which should be a last resort. As is often the case with CSS, we have a plethora of options available to us.

Option 1: Create an additional class

.primary.navbar .nav > li > a {
    padding: 5px 5px 5px;

Option 2: Repeat a class

.navbar.navbar .nav > li > a {
    padding: 5px 5px 5px;


Repeated occurrances of the same simple selector are allowed and do increase specificity.

Option 3: Use same class, but define this class after bootstrap

 <link rel="stylesheet" href="bootstrap.css">
 <link rel="stylesheet" href="modify_bootstrap.css">

If you didn't know this already, type="text/css" isn't required in HTML5

.navbar .nav > li > a {
    padding: 5px 5px 5px;


You may add a class my-padding to your element and use the following in your app.css which you link to your html after bootstrap.css

.navbar-nav > li > .my-padding {
    padding: 5px 5px 5px;