Search code examples
cssreactjsheightwebcam

React webcam height could not be set


I tried to set webcam height as below using '%' (tried setting both from js page and from css).

              <div>
                {!imgSrc && <div>                      
                <>
                    {/* className="video-stream" */}
                    <Webcam width={100 + '%'}    // height={50 + '%'} does not work
                            audio={false}
                            ref={webcamRef}
                        screenshotFormat="image/jpeg"
                       // forceScreenshotSourceSize="true"
                            videoConstraints={{
                                ...videoConstraints,
                                facingMode
                            }}
                        />
                    </>
                   
                    <Grid container={true} justifyContent='center' alignItems='center' spacing={1}>                       
                        <button onClick={capture}> Capture </button>
                </Grid>
              </div>}

Css:

Here in css, when I set in pixel, it works on desktop but doesn't get applied for mobile. Any input would be appreciated.

For mobile and desktop:

 @media only screen and (min-width: 360px) and (max-width: 750px) {
    .video-stream {
        height: 210px;
        /* width: 290px; */
    }
 }
@media only screen and (min-width: 751px) {
    .video-stream {
        height: 400px;
       /* width: 530px; */
   }
}

Solution

  • You can add a className to the Webcam component and use % in the css file, then add the pixel size to a parent element according to your needs. For example if I wrap the Webcam component in a div element it can be something like:

    <div  className="video-stream">
              <Webcam
                className="webcam"
                audio={false}
                ref={webcamRef}
                screenshotFormat="image/jpeg"
              />
          </div> 
    

    in the css file:

    .webcam{
      width: 100%;
      height: 100%;
    }