4

My component looks like this:

<Card>
    <CardMedia>
        <img src="http://images.memes.com/character/meme/evil-toddler"/>
    </CardMedia>
</Card>

I have noticed that the image uses almost 100% of the width of the page, which is undesirable in my situation.

What I would like to do is define the width of the image (or the Card if possible) to depend on the DPI / resolution of the screen, using something like CSS's @media.

For example, if DPI > 720dp, the card should occupy the 60% of the screen, else 90%. Something like that.

I tried with a custom CSS but it doesn't work because the library uses inline CSS and it overwrites my attributes.

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230
Minas Mina
  • 2,058
  • 3
  • 21
  • 35

2 Answers2

5

You can override the styles on the Card itself. To do this using the screen resolution you can get the width using window.screen.availWidth. Here is an example:

import React from 'react';
import {Card, CardMedia} from 'material-ui/Card';

/**
 * Render the card with the given width as a percent.
 * @param {String} widthAsPercent
 * @returns {XML}
 */
let renderCardWithWidth = (widthAsPercent) => {
  return <Card style={{width:widthAsPercent}}>
    <CardMedia>
      <img src='http://images.memes.com/character/meme/evil-toddler'/>
    </CardMedia>
  </Card>;
};

export default class ResponsiveCard extends React.Component {
  render() {
    let width = window.screen.availWidth;
    if (width > 720) {
      return renderCardWithWidth('60%');
    } else {
      return renderCardWithWidth('90%');
    }
  }
}
wayofthepie
  • 411
  • 4
  • 8
1

In MUI v5, you can use the sx prop and pass a responsive width where the value changes depending on the current breakpoint:

<Card
  sx={{
    width: {
      sx: 1.0, // 100%
      sm: 250,
      md: 350,
    },
  }}
>

Live Demo

Codesandbox Demo

NearHuscarl
  • 66,950
  • 18
  • 261
  • 230