Extending Bootstrap 3 LESS .btn-group not working

2020-02-02 02:41发布

Ultimately I'm trying to accomplish the following styles with LESS.

<div class="filter btn-group">
    <button class="btn btn-default" type="button" data-filter="*">show all</button>
    <button class="btn btn-default" type="button" data-filter=".cd">CD</button>
    <button class="btn btn-default" type="button" data-filter=".vinyl">Vinyl</button>    
</div>

I have the following HTML

<div class="filter">
    <button type="button" data-filter="*">show all</button>
    <button type="button" data-filter=".cd">CD</button>
    <button type="button" data-filter=".vinyl">Vinyl</button>
</div>

And I have this in a LESS file with imports of Bootstrap 3

.filter {
    .btn-group;
    button {
        .btn;
        .btn-default;
    }
}

When adding .btn and .btn-default to the button works just fine. But adding .btn-group to the wrapper ".filter" doesn't work. I can't figure out what I'm doing wrong. If I add the class .btn-group manually to the

class="filter btn-group"
It works.

1条回答
We Are One
2楼-- · 2020-02-02 02:55

EDITED

While I couldn't think of a way to fully accomplish what you wanted, with some help and inspiration from @seven-phases-max, I was able to adapt that gist to get your desired result.

To get a picture of how it works, the 'steps' are: First, treat the button selector as .btn.btn-default. Second, find all instances of the .btn-group selector and replace it with .filter. Then, finally, find all instances of .btn within the .filter and replace those with button.

You can accomplish this with extend (available in Less v1.4.0+). Here is a simple example of the less file:

@import "bootstrap.less";
button {
    .btn-default();
    &:extend(.btn, .btn.btn-default all);
}
.filter:extend(.btn-group all) {}
.filter > button:extend(.btn-group > .btn all) {}
.filter button + button:extend(.btn-group .btn + .btn all) {}

You need to make sure that any extend is placed after your other imports because the extend all acts like (a non-destructive) search & replace. So, the first extend above, for example, finds all instances of .btn within any rule selector and makes a copy of the selector, replacing .btn with button.

The resulting output allows the following to be styled like a btn-group:

<div class="filter">
  <button type="button">BUTTON ONLY</button>
  <button type="button">BUTTON ONLY</button>
  <button type="button">BUTTON ONLY</button>
</div>

CAVEATS

  1. As pointed out in several comments by seven-phases-max, this is going to add a fair bit of additional weight to your output because it's a non-destructive search and replace. It adds about 9Kb to the unminified/uncompressed output.
  2. You cannot use this type of extend the labels for checkboxes or radio buttons with the data-toggle="buttons" attribute as the BUTTON DATA-API inside button.js is looking specifically for the class .btn versus looking for a button element.
查看更多
登录 后发表回答