How can I customize Twitter Bootstrap's CSS using LESSCSS variables?

穿精又带淫゛_ 提交于 2019-11-27 14:11:32

The correct approach is to import the bootstrap assets first, then define the custom values with LESS variables. So, given the directory structure in the question:

If you're using Bootstrap version 2.x:

/* import bootstrap components from bootstrap-dedicated folder */
@import "../../../bootstrap/less/bootstrap.less";
@import "../../../bootstrap/less/responsive.less";

/* custom settings that deviate from Bootstrap's default values */
@sansFontFamily: Trebuchet MS, Tahoma, sans-serif, Arial;
@baseFontSize: 11px;
@baseLineHeight: 18px;

If you're using Bootstrap version 3.x:

/* import bootstrap components from bootstrap-dedicated folder */
@import "../../../bootstrap/less/bootstrap.less";

/* custom settings that deviate from Bootstrap's default values */
@font-family-sans-serif: Trebuchet MS, Tahoma, sans-serif, Arial;
@font-size-base: 11px;
@line-height-base: 18px;

Complete list of variables can be found in variables.less file.

PeterVR's advice to move the custom variable declarations below the bootstrap @import statements is correct according to the docs here http://lesscss.org/#-variables. This states:

When defining a variable twice, the last definition of the variable is used, searching from the current scope upwards. For instance:

@var: 0;
.class1 {
    @var: 1;
    .class {
        @var: 2;
        three: @var;
        @var: 3;
    }
    one: @var;
}

Compiles to:

.class1 .class {
    three: 3;
}
.class1 {
    one: 1;
}

(sample code edited - there's a couple of typos in their version!)

So I would guess the compilation sequence is something like:

  1. Process all @imports to build a single chunk of LESS code
  2. Walk through the LESS code and gather up all the variable declarations (per scope block)
  3. Any variable declaration value replaces any previous instance of the same name (per scope block)
  4. Replace variable placeholders with variable values

This would explain why the value of .class1 .class { three: is 3 even though it's declared before the @var: 3; declaration.

Hello I got a better way from random internet search

http://ollomedia.com/using-twitter-bootstrap-the-right-way/

Example source code , Please download and checkout

http://ollomedia.com/wp-content/uploads/sample.zip

I did something similar recently and the best approach I found was to create my own "variables_override.less" and import this after importing the standard variables.less in bootstrap.less and responsive.less. Then compile both files as normal and your variables will override the bootstrap defaults

This approach does involve modifing bootsrap.less and responsive.less but in a very minimal way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!