Search code examples
cssreactjsstylescalc

Use calc function in CSS in JS in React component


I am working on one react component in which I need to use calc function in styles

const styles = {
  spotImg:{
    maxWidth:"100%",
    maxHeight:"100%"
  },
  spotCont:{
    width: /*here want to use calc with screen width*/
  }
}

I want to use screen width with calc function in the above style code in react js component.


Solution

  • const styles = {
      spotImg:{
        maxWidth:"100%",
        maxHeight:"100%"
      },
      spotCont:{
        width: "calc(100vw)", 
         fallbacks:["-moz-calc(100vw)", 
         "-webkit-calc(100vw)",
         "-o-calc(100vw)
         ]
      }
    }
    

    Put the calc function in double quotations, and then you can use the CSS's vw to access screen width. Ie, 100vw provides you with the entire screen width. 100vw - 250px provides you with 250px less than the screen width, for example.

    EDIT: Added fallbacks based on OP's comment about browser not accepting calc function.