Now I'm using LESS to customize Bootstrap to my own website. I have a problem with LESS's mixins.

For example, the following LESS code:

.Article {
  margin-left: 5px;
  .Small {
      color: #111;
  }
}
.Small {
    font-size: 5px;
}

.MyArticle {
  .Article;
  .Address {
    .Small;
  }
}

is compiled to the following CSS:

.Article {
  margin-left: 5px;
}
.Article .Small {
  color: #111;
}
.Small {
  font-size: 5px;
}
.MyArticle {
  margin-left: 5px;
}
.MyArticle .Small {
  color: #111;
}
.MyArticle .Address {
  color: #111;
}

However, in addition to the above generated CSS, I want to make ".MyArticle .Address" small:

.MyArticle .Address {
  font-size: 5px;
}

What is the best way?

EDITED:

In the above example of LESS code, the .Article and .Small are the library's class, and I don't want to modify them.

有帮助吗?

解决方案

The Problem is Scoping

In your original layout, by including .Article at the same level as .Address is defined, then it is using the .Small from the .Article as the only mixin, because it is the "local" .Small in the .Address context. To avoid this, the .Article must be isolated to its own block. But then you lose the color being picked up from it's .Small, so it must be explicitly included back into .Address through a namespaced call. The code ends up like this:

LESS

.Article {
  margin-left: 5px;
  .Small {
      color: #111;
  }
}
.Small {
    font-size: 5px;
}

.MyArticle {
  .Address {
     .Small;
     .Article > .Small;
  }
  & {.Article;}
}

CSS Output

.Article {
  margin-left: 5px;
}
.Article .Small {
  color: #111;
}
.Small {
  font-size: 5px;
}
.MyArticle {
  margin-left: 5px;
}
.MyArticle .Address {
  font-size: 5px;
  color: #111;
}
.MyArticle .Small {
  color: #111;
}

其他提示

Not really sure, but possibly this code:

.Article {
  margin-left: 5px;
  .Small {
      color: #111;
  }
}
.Small {
    font-size: 5px;
}

.MyArticle {
  .Article;
  .Address {
    .Small;
    font-size: 5px;
  }
}

Try extend:

.Article {
  margin-left: 5px;
  .Small {
      color: #111;
  }
}
.Small {
    font-size: 5px;
}

.MyArticle {
  .Article;
  .Address {
    &:extend(.Small);
  }
}

This compiles to:

.Article {
  margin-left: 5px;
}
.Article .Small {
  color: #111;
}
.Small,
.MyArticle .Address { //<-- this
  font-size: 5px;
}
.MyArticle {
  margin-left: 5px;
}
.MyArticle .Small {
  color: #111;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top