how to alias class name in css or sass

2019-01-23 11:14发布

Can I create an alias to a css class?

I am using this font-awesome and I am trying to create an alias name for some of the icon classes. So that .icon-globe will also called .globe.

How can I accomplish such thing?

5条回答
看我几分像从前
2楼-- · 2019-01-23 11:27

You can apply the same styles to several classes using plain css comma separated selectors:

.icon-globe, .globe {
  //styles
}

Will apply the same styles to <i class="icon-globe"> and <i class="globe">.

查看更多
Emotional °昔
3楼-- · 2019-01-23 11:28

You may be interested in CSS Crush which allows you to create aliases http://the-echoplex.net/csscrush/#core--selector-aliases

Usage

@selector globe :any( .icon-globe, .globe );

:globe {
  color: red;
}

Outputs

.icon-globe, .globe {
  color: red;
}
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-23 11:39

Easiest way I can think of is to use javascript/jquery.

jQuery:

$(document).ready(function() {
  $('.globe').addClass('icon-globe');
});
查看更多
Root(大扎)
5楼-- · 2019-01-23 11:42

There's no such thing as aliasing. Sass does have the @extend directive, but the solution isn't entirely obvious until you look into the source.

Source: https://github.com/FortAwesome/Font-Awesome/blob/master/sass/font-awesome.scss

[class^="icon-"]:before,
[class*=" icon-"]:before {
  font-family: FontAwesome;
  font-weight: normal;
  font-style: normal;
  display: inline-block;
  text-decoration: inherit;
}

// snip

.icon-globe:before                { content: "\f0ac"; }

Even if you made .globe extend .icon-globe, you'll be missing out on most of what makes the FontAwesome styles because of how they built the selector. You have to extend the other selector as well.

.globe {
    @extend .icon-globe;
    @extend [class^="icon-"];
}

Generates:

[class^="icon-"]:before, .globe:before,
[class*=" icon-"]:before {
  font-family: FontAwesome;
  font-weight: normal;
  font-style: normal;
  display: inline-block;
  text-decoration: inherit; }

.icon-globe:before, .globe:before {
  content: "\f0ac"; }

Note that the icon- prefix was deliberate. You get smaller CSS files this way, rather than attaching all of those styles to all ~200 classes that come with FontAwesome. You can do it, but I don't think the result is very good.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-23 11:42

I know this is an older question but I am answering this because the thread looks incomplete...

You can easily do this with SASS by extending the icon-globe class

.globe{
    @extend .icon-globe !optional;
}

The output CSS will be as,

.globe,.icon-globe{
   /* CSS Properties */
}

Considering the new class names of Font-Awesome, you will be need to using the .fa-globe with multiple class extending

.globe{
    @extend .fa, .fa-globe !optional;
}

The output CSS will be as,

.fa,.globe{
 /* ... */
}

.globe,.fa-globe{
   /* CSS Properties */
}
查看更多
登录 后发表回答