Can Bootstrap 3 Grid Be Extended?

2019-03-20 08:15发布

I'm working on a project where we are leaving the Bootstrap less files untouched. We also do not want to use Bootstrap classes in the HTML, since we may not use it in the future. I'm experimenting with using the "extend" feature to group our class names with the BS version in the style sheet. This has worked well except with the grid columns. Since the column class names are built with the ".make-grid" mixin, I can't extend them. Any thoughts on how to not use BS classnames for the grid AND not bloat the CSS?

If you are unfamiliar with the extend option, you can view the documentation here: http://www.lesscss.org/#-extend

//Not ideal because it duplicates declarations.
.mytable {
  .table;
}

//Good because it groups the selectors instead of duplicating declarations.
.mytable {
  &:extend(.table all);
}

//This does not work, but I wish it did.
.search {
  &:extend(.col-sm-6); 
}

//This is not ideal because it duplicates declarations.
.search {
  .make-sm-column(6);
}

3条回答
Rolldiameter
2楼-- · 2019-03-20 08:23

.col-sm-6 is dynamic generate on compilation time, so can not extended.

.search {
  .make-sm-column(6);
}

generates:

.search {
  position: relative;
  min-height: 1px;
  padding-left: 15px;
  padding-right: 15px;
}
@media (min-width: 768px) {
  .search {
    float: left;
    width: 50%;
  }
}

Which is a little overhead, but small in relation to the other source.

In theory you can can compile twice:

  1. lessc bootstrap.less > bootstrap.css
  2. lessc test.less > test.css, with test.less:

    @import (less) "bootstrap.css";
    .search {
      &:extend(.col-sm-6);
    }
    

doing a diff over bootstrap.css and test.css i found as expected among others:

>   .col-sm-6,
>   .search {
1010c1082,1093
<   .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
---

recompiling seems futher:

  • put .col-md-* etc. on a new line
  • change for example 0.75 to .75
  • change (enabled = false) into (enabled=false)

which all make no sense on the first sight

查看更多
Root(大扎)
3楼-- · 2019-03-20 08:29

You can extend columns in SASS

.cols
  @extend .row
  .col1, .col2
    @extend .col-xs-6
查看更多
贼婆χ
4楼-- · 2019-03-20 08:43

As said, the grid can't really be extended so an alternate solution must be found. Even though the accepted answer is right I'd like to share another approach that can be considered.

  1. Generate your grid or simply copy all the relevant classes (.col-xs-1, .col-xs-2 ecc.) from the css and put them in a new Less file named something like grid.less (note the less extension).

  2. Import this file in your main .less file like so:

    @import (reference) "grid.less";

  3. Now you can &:extend(.col-sm-6);

Importing using (reference) will generate a css without any trace of .col-xx-x classes and will only write the values that you actually use.

查看更多
登录 后发表回答