programing

jss 색상의 불투명도를 변경하는 방법

cafebook 2023. 3. 14. 21:53
반응형

jss 색상의 불투명도를 변경하는 방법

현재 저는 jss를 사용하여 요소에 색상을 추가하기 위해 아래 코드를 사용하고 있습니다.

const styleSheet = theme => ({
  root: {
     backgroundColor: theme.colors.red,
  },
})

색상에 따라 불투명도를 더하는 기능이 있는지 알고 싶습니다.theme.colors.red.

샘플 smt like:backgroundColor: color(theme.colors.red, .05),

머티리얼 UI에는colorManipulator 유틸리티 파일, 여기에는alpha기능:

import { alpha } from '@material-ui/core/styles/colorManipulator';

/**
 * Sets the absolute transparency of a color.
 * Any existing alpha values are overwritten.
 * @param {string} color - CSS color, i.e. one of: #nnn, #nnnnnn, rgb(), rgba(), hsl(), hsla(), color()
 * @param {number} value - value to set the alpha channel to in the range 0 - 1
 * @returns {string} A CSS color string. Hex input values are returned as rgb
 */

{
    backgroundColor: alpha(theme.colors.red, 0.5)
}

Mui v5의 경우:

import { alpha } from "@mui/material";

또는 npm부터 컬러 라이브러리를 추가하여 컬러를 조작할 수도 있습니다.

import Color from 'color';

{
    backgroundColor: Color(theme.colors.red).alpha(0.5).string()
}

또는 Material UI Next에서 제공하는 페이드 기능을 사용할 수 있습니다.

import {fade} from 'material-ui/styles/colorManipulator';

const theme = createMuiTheme({
  overrides: {
    MuiButton: {
      root: {
        boxShadow: `0 4px 8px 0 ${fade(defaultTheme.palette.primary[500], 0.18)}`,
      }
    },
  }
});

export default theme;

작동원리는 다음과 같습니다.https://github.com/mui-org/material-ui/blob/v1-beta/src/styles/colorManipulator.js#L157-L164

또 다른 솔루션은 https://github.com/styled-components/polished의 유사한 색상 기능을 사용하는 것입니다.

색상에 정의된 알파 채널이 없는 경우 다음을 수행할 수도 있습니다.

backgroundColor: theme.colors.red + '00' 

그러면 알파 채널이 0으로 설정되므로 투명합니다.다음 사이에 임의의 값을 추가할 수 있습니다.'00'로.'ff'

다음 방법으로 해결 방법을 찾았습니다.

 backgroundColor: theme.utils.rgba(theme.axColor.black, 0.7),

MUI v5에서는 다음과 같이 동작합니다.

import { alpha } from '@mui/material';

...

MuiContainer: {
      styleOverrides: {
        root: {
          '&.MuiContainer-asideWithImage': {
            backgroundColor: alpha(MY_COLOR, 0.78),
          },
        },
      },
    },

...

이러한 답변 중 일부는 사용되지 않는 Material-UI 기능을 참조하고 있습니다.현재 선호되는 접근법은alpha:

import { alpha } from "@material-ui/core";

...
                 // yields rgba(255,255,255,0.85)
backgroundColor: alpha(theme.palette.background.paper, 0.85) 

RGBA 값을 사용할 수 있습니다.

const styleSheet = theme => ({
  root: {
     backgroundColor: 'rgba(255, 255, 255, 0.5)',
  },
})

https://facebook.github.io/react-native/docs/colors.html

또 다른 가능성은 다음과 같습니다.

import color from "color"

const themeColorsRed = color
  .rgb(theme.colors.red)
  .array()

다음 작업을 수행할 수 있습니다.

{
  backgroundColor: `rgba(${themeColorsRed}, 0.05)`,
}

8자리 16진수 코드도 유효합니다.

const styleSheet = theme => ({
  root: {
     backgroundColor: '#ffffff80',
  },
})

언급URL : https://stackoverflow.com/questions/47268652/jss-how-to-change-opacity-for-a-color

반응형