Minas Mina
Minas Mina

Reputation: 2107

Responsive width for Card

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.

Upvotes: 4

Views: 11251

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81653

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

Upvotes: 2

wayofthepie
wayofthepie

Reputation: 606

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%');
    }
  }
}

Upvotes: 5

Related Questions