Sass - 将Hex转换为RGBa以获得背景不透明度

时间:2012-06-07 09:49:45

标签: css sass background-color mixins rgba

我有以下Sass mixin,这是 RGBa示例的半完整修改:

@mixin background-opacity($color, $opacity: .3) {
    background: rgb(200, 54, 54); /* The Fallback */
    background: rgba(200, 54, 54, $opacity);
} 

我已应用$opacity确定,但现在我陷入$color部分。 我将发送到mixin的颜色将是HEX而不是RGB。

我的示例用法是:

element {
    @include background-opacity(#333, .5);
}

如何在此mixin中使用HEX值?

5 个答案:

答案 0 :(得分:362)

rgba() function可以接受单个十六进制颜色以及十进制RGB值。例如,这可以正常工作:

@mixin background-opacity($color, $opacity: 0.3) {
    background: $color; /* The Fallback */
    background: rgba($color, $opacity);
}

element {
     @include background-opacity(#333, 0.5);
}

但是,如果您需要将十六进制颜色分解为RGB组件,则可以使用red()green()blue()函数执行此操作:

$red: red($color);
$green: green($color);
$blue: blue($color);

background: rgb($red, $green, $blue); /* same as using "background: $color" */

答案 1 :(得分:99)

内置混音:transparentize($color, $amount);

background-color: transparentize(#F05353, .3);

金额应介于0到1之间;

Official Sass Documentation (Module: Sass::Script::Functions)

答案 2 :(得分:27)

SASS有一个内置rgba() function来评估值。

['attribute1' => 'value1', ..]

E.g。

rgba($color, $alpha)

使用您自己的变量的示例:

rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)

输出:

$my-color: #00aaff;
$my-opacity: 0.5;

.my-element {
  color: rgba($my-color, $my-opacity);
}

答案 3 :(得分:6)

你可以尝试这个解决方案,是最好的... url(github

// Transparent Background
// From: http://stackoverflow.com/questions/6902944/sass-mixin-for-background-transparency-back-to-ie8

// Extend this class to save bytes
.transparent-background {
  background-color: transparent;
  zoom: 1;
}

// The mixin
@mixin transparent($color, $alpha) {
  $rgba: rgba($color, $alpha);
  $ie-hex-str: ie-hex-str($rgba);
  @extend .transparent-background;
  background-color: $rgba;
  filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#{$ie-hex-str},endColorstr=#{$ie-hex-str});
}

// Loop through opacities from 90 to 10 on an alpha scale
@mixin transparent-shades($name, $color) {
  @each $alpha in 90, 80, 70, 60, 50, 40, 30, 20, 10 {
    .#{$name}-#{$alpha} {
      @include transparent($color, $alpha / 100);
    }
  }
}

// Generate semi-transparent backgrounds for the colors we want
@include transparent-shades('dark', #000000);
@include transparent-shades('light', #ffffff);

答案 4 :(得分:2)

如果您需要混合使用变量透明度和Alpha透明度的颜色,并且使用包含rgba()函数的解决方案,则会出现类似

的错误
      background-color: rgba(#{$color}, 0.3);
                       ^
      $color: #002366 is not a color.
   ╷
   │       background-color: rgba(#{$color}, 0.3);
   │                         ^^^^^^^^^^^^^^^^^^^^

类似的事情可能有用。

$meeting-room-colors: (
  Neumann: '#002366',
  Turing: '#FF0000',
  Lovelace: '#00BFFF',
  Shared: '#00FF00',
  Chilling: '#FF1493',
);
$color-alpha: EE;

@each $name, $color in $meeting-room-colors {

  .#{$name} {

     background-color: #{$color}#{$color-alpha};

  }

}
相关问题