是否可以从 SASS mixin 中测试当前元素类型? [英] Is it possible to test for the current element type from within a SASS mixin?

查看:52
本文介绍了是否可以从 SASS mixin 中测试当前元素类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 mixin 可以绘制这样的按钮:

I have a mixin that draws a button like this:

@mixin button {
  border: 1px solid $orange;
  background: $orange;
  padding:0;
  height:27px;
  text-transform: uppercase;
  color:white;
  display:block;
  // if I'm styling an a tag padding-top:10px 10px 0 10px;
}

我希望能够做到这一点:

I want to be able to do this:

button.my_button {
  @include button;
}

a.my_button {
  @include button;
}

第二个需要一些额外的自定义代码才能很好地工作.是否可以在 mixin 中包含一个条件来检查我是否在为 a 标签设置样式,或者我是否需要编写第二个 mixin?

The second one requires some additional custom code to work nicely. Is is possible to include a conditional in the mixin that checks to see if I'm styling an a tag, or do I need write a second mixin?

推荐答案

Sass 3.3 及更早版本

在 mixin 中,没有.如果您对扩展持开放态度,则可以非常接近:

Sass 3.3 and older

Within a mixin, no. If you're open to extends, you can get pretty close:

$orange: lighten(orange, 10%);

%button {
  border: 1px solid $orange;
  background: $orange;
  padding:0;
  height:27px;
  text-transform: uppercase;
  color:white;
  display:block;
}

a%button {
    padding-top:10px 10px 0 10px;
}

button.my_button {
  @extend %button;
}

a.my_button {
  @extend %button;
}

编译为:

button.my_button, a.my_button {
  border: 1px solid #ffb733;
  background: #ffb733;
  padding: 0;
  height: 27px;
  text-transform: uppercase;
  color: white;
  display: block;
}

a.my_button {
  padding-top: 10px 10px 0 10px;
}

Sass 3.4 及更新版本

从 3.4 开始,我们可以检查和操作选择器.

Sass 3.4 and newer

Starting with 3.4 we have the ability to examine and manipulate the selector.

$orange: lighten(orange, 10%);

@mixin button {
  border: 1px solid $orange;
  background: $orange;
  padding:0;
  height:27px;
  text-transform: uppercase;
  color:white;
  display:block;

  @if is-superselector('a', &) {
    padding-top: 10px 10px 0 10px;
  }
}

button {
  @include button;
}

b a.foo {
  @include button;
}

输出:

button {
  border: 1px solid #ffb733;
  background: #ffb733;
  padding: 0;
  height: 27px;
  text-transform: uppercase;
  color: white;
  display: block;
}

b a.foo {
  border: 1px solid #ffb733;
  background: #ffb733;
  padding: 0;
  height: 27px;
  text-transform: uppercase;
  color: white;
  display: block;
  padding-top: 10px 10px 0 10px;
}

这篇关于是否可以从 SASS mixin 中测试当前元素类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆