development

CSS 색상 변수에 불투명도를 어떻게 적용합니까?

big-blog 2020. 9. 9. 21:57
반응형

CSS 색상 변수에 불투명도를 어떻게 적용합니까?


전자로 앱을 디자인하고 있으므로 CSS 변수에 액세스 할 수 있습니다. 다음에서 색상 변수를 정의했습니다 vars.css.

:root {
  --color: #f0f0f0;
}

에서이 색상을 사용하고 싶지만 main.css일부 불투명도를 적용했습니다.

#element {
  background: (somehow use var(--color) at some opacity);
}

어떻게하면 되나요? 전처리 기가 아니라 CSS 만 사용하고 있습니다. 모든 CSS 답변을 선호하지만 JavaScript / jQuery를 수락합니다.

opacity투명하지 않아야하는 배경 이미지를 사용하고 있기 때문에 사용할 수 없습니다 .


기존 색상 값을 가져와 여기에 알파 채널을 적용 할 수 없습니다. 즉,와 같은 기존 16 진수 값을 가져 와서 #f0f0f0알파 구성 요소를 제공하고 결과 값을 다른 속성과 함께 사용할 수 없습니다 .

그러나 사용자 지정 속성을 사용하면 16 진수 값을와 함께 사용할 RGB 3 색으로 변환하고 rgba(), 해당 값을 사용자 지정 속성 (쉼표 포함!)에 저장하고, 사용하는 값을 원하는 알파 값이 var()있는 rgba()함수 대체하면 됩니다. 그냥 일이야:

:root {
  /* #f0f0f0 in decimal RGB */
  --color: 240, 240, 240;
}

body {
  color: #000;
  background-color: #000;
}

#element {
  background-color: rgba(var(--color), 0.5);
}
<p id="element">If you can see this, your browser supports custom properties.</p>

이것은 사실 이기에는 너무 좋아 보인다. 1 어떻게 작동합니까?

커스텀 속성의 값으로 치환된다는 사실에 놓여 마법 으로는 교체 할 때 var(), 특성 값에 대한 참조를 하기 전에 그 속성의 값이 계산된다. 지금까지 사용자 지정 속성에 관한 한대로의 가치 있음이 수단 --color귀하의 예제에서 모두에서 컬러 값이 아닙니다 까지var(--color) 표현은 색상 값 (및 해당 맥락에서) 기대 어딘가에 나타납니다. 에서 2.1 CSS의-변수 사양의 :

사용자 지정 속성에 허용되는 구문은 매우 관대합니다. <declaration-value> 프로덕션은 시퀀스에 <bad-string-token>, <bad-url-token>, unmatched <)-token>, <]-가 포함되지 않는 한 하나 이상의 토큰 시퀀스와 일치합니다. token>, <}-token> 또는 "!"값을 가진 최상위 <semicolon-token> 토큰 또는 <delim-token> 토큰.

예를 들어 다음은 유효한 사용자 지정 속성입니다.

--foo: if(x > 5) this.width = 10;

이 값은 일반 속성에서 유효하지 않기 때문에 변수로 분명히 쓸모가 없지만 JavaScript에 의해 읽고 작동 할 수 있습니다.

그리고 섹션 3 :

속성에 하나 이상의 var () 함수가 포함되어 있고 해당 함수가 구문 상 유효하면 전체 속성의 문법이 구문 분석시 유효한 것으로 가정해야합니다. var () 함수가 대체 된 후 계산 된 값 시간에만 구문 검사가 수행됩니다.

즉, 240, 240, 240위에서 은 선언이 계산 되기 전에rgba() 함수 로 직접 대체 됩니다. 그래서 이거:

#element {
  background-color: rgba(var(--color), 0.5);
}

rgba()4 개 이상의 쉼표로 구분 된 숫자 값을 예상 하기 때문에 처음 에는 유효한 CSS로 보이지 않는 것으로 보입니다 .

#element {
  background-color: rgba(240, 240, 240, 0.5);
}

물론 완벽하게 유효한 CSS입니다.

한 단계 더 나아가 알파 구성 요소를 자체 사용자 정의 속성에 저장할 수 있습니다.

:root {
  --color: 240, 240, 240;
  --alpha: 0.5;
}

동일한 결과로 대체하십시오.

#element {
  background-color: rgba(var(--color), var(--alpha));
}

이렇게하면 즉석에서 바꿀 수있는 다양한 알파 값을 가질 수 있습니다.


1 Well, it is, if you're running the code snippet in a browser that doesn't support custom properties.


I know the OP isn't using a preprocessor, but I would have been helped if the following information was part of the answer here (I can't comment yet, otherwise I would have commented @BoltClock answer.

If you are using, e.g. scss, the answer above will fail, because scss attempts to compile the styles with a scss-specific rgba()/hsla() function, which requires 4 parameters. However, rgba()/hsla() are also native css functions, so you can use string interpolation to bypass the scss function.

Example (valid in sass 3.5.0+):

:root {
    --color_rgb: 250, 250, 250;
    --color_hsl: 250, 50%, 50%;
}

div {
    /* This is valid CSS, but will fail in a scss compilation */
    background-color: rgba(var(--color_rgb), 0.5);
    
    /* This is valid scss, and will generate the CSS above */
    background-color: #{'rgba(var(--color_rgb), 0.5)'};
}
<div></div>

Note that string interpolation will not work for non-CSS scss functions, such as lighten(), because the resulting code would not be functional CSS. It would still be valid scss though, so you would receive no error in compilation.


This is indeed possible with CSS. It's just a bit dirty, and you'll have to use gradients. I've coded a small snippet as example, take note that for dark backgrounds, you should use the black opacity, as for light- the white ones.:

:root {
  --red: rgba(255, 0, 0, 1);
  --white-low-opacity: rgba(255, 255, 255, .3);
  --white-high-opacity: rgba(255, 255, 255, .7);
  --black-low-opacity: rgba(0, 0, 0, .3);
  --black-high-opacity: rgba(0, 0, 0, .7);
}

div {
	width: 100px;
	height: 100px;
	margin: 10px;
}
    
    
.element1 {
	background: 
        linear-gradient(var(--white-low-opacity), var(--white-low-opacity)) no-repeat,
	linear-gradient(var(--red), var(--red)) no-repeat;
}

.element2 {
	background: 
        linear-gradient(var(--white-high-opacity), var(--white-high-opacity)) no-repeat,
	linear-gradient(var(--red), var(--red)) no-repeat;
}
    
.element3 {
	background: 
        linear-gradient(var(--black-low-opacity), var(--black-low-opacity)) no-repeat,
	linear-gradient(var(--red), var(--red)) no-repeat;
}

.element4 {
	background: 
        linear-gradient(var(--black-high-opacity), var(--black-high-opacity)) no-repeat,
	linear-gradient(var(--red), var(--red)) no-repeat;
}
<div class="element1">hello world</div>
<div class="element2">hello world</div>
<div class="element3">hello world</div>
<div class="element4">hello world</div>


:root{
--color: 255, 0, 0;
}

#element{
    background-color: rgba(var(--color), opacity);
}

where you replace opacity with anything between 0 and 1


I was in a similar situation, but unfortunately the given solutions did not work for me, as the variables could be anything from rgb to hsl to hex or even color names.
I solved this issue now, by applying the background-color and the opacity to a pseudo :after element:

.container {
    position: relative;
}

.container:after {
    content: "";
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    background-color: var(--color);
    opacity: 0.3;
}

The styles might need to be changed a little, depending on the element the background should be applied to.
Also it might not work for all situations, but hopefully it helps in some cases, where the other solutions can't be used.


You can set specific variable/value for each color - the original and the one with opacity:

:root {
  --color: #F00;
  --color-opacity: rgba(255, 0, 0, 0.5);
}
#a1 {
  background: var(--color);
} 
#a2 {
  background: var(--color-opacity);
}
<div id="a1">asdf</div>
<div id="a2">asdf</div>

If you can't use this and you are ok with javascript solution, you can use this one:

$(function() {
  $('button').click(function() {
    bgcolor = $('#a2').css('backgroundColor');
    rgb_value = bgcolor.match(/\d+,\s?\d+,\s?\d+/)[0]
    $('#a2').css('backgroundColor', 'rgba(' + rgb_value + ', 0.5)');
  });
});
:root {
  --color: #F00;
}
#a1 {
  background: var(--color);
} 
#a2 {
  background: var(--color);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="a1">asdf</div>
<div id="a2">asdf</div>
<button>Click to change opacity</button>


For using rgba() with general css variable, try this:

  1. Declare your color inside :root, but don't use rgb() as other answers do. just write the value

:root{
  --color : 255,0,0;
  }

  1. Use --color variable using var() as other answers

#some-element {
  color : rgba(var(--color),0.5);
}


In CSS you should be able to either use rgba values:

#element {
  background: rgba(240, 240, 240, 0.5);
}

or just set the opacity:

#element {
  background: #f0f0f0;
  opacity: 0.5;    
}

If you love hex colors like me there is another solution. The hex value is 6 digits after that is the alpha value. 00 is 100% transparency 99 is about 75% then it uses the alphabet 'a1-af' then 'b1-bf' ending with 'ff' which is 100% opaque.

:root {
--color: #F00;
}

#element {
background: var(--color)f6;
}

참고URL : https://stackoverflow.com/questions/40010597/how-do-i-apply-opacity-to-a-css-color-variable

반응형