Setting the height of an element based on the height of its background image

Hey there! I'm currently working with this component in my app, and right now, the height of the ButtonBase element is fixed. I fetch an image from the backend and use it as a backgroundImage for the ImageImagine component. I want to dynamically adjust the height of the ButtonBase so that the background image in ImageImagine can maintain its original aspect ratio.

import React, { useState } from 'react';
import {
  Box,
  ButtonBase as MuiButtonBase,
  IconButton,
  Typography,
  styled,
} from '@mui/material';

import Label from './Label';
import Favorite from './Favorite';
import MintingContextButton from './MintingContextButton';

import StatusLabel from 'src/components/StatusLabel';
import PublicLabel from 'src/components/PublicLabel';

import { IMAGINE_STATUS } from 'src/constants';
import { authDomain } from 'src/config';

const ButtonBase = styled(MuiButtonBase)(({ theme }) => ({
  position: 'relative',
  height: 342,
  width: '100%',
  borderRadius: 32,
  [theme.breakpoints.down('xs')]: {
    width: '100% !important', // Overrides inline-style
    height: 326,
  },
  '&:hover': {
    '& .imageTitle': {
      opacity: 1,
      transition: theme.transitions.create('opacity'),
      zIndex: 1,
    },
    '& .imageBackdrop': {
      opacity: 0.7,
    },
    '& .MuiIconButton-favorite': {
      opacity: 1,
      transition: theme.transitions.create('opacity'),
      zIndex: 12,
    },
    '& .MuiButton-minting': {
      opacity: 1,
      transition: theme.transitions.create('opacity'),
      zIndex: 12,
    },
  },
}));

const ContextContainer = styled('span')(() => ({
  position: 'absolute',
  width: '100%', // should be on if a real mint button
  height: '100%',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'space-between',
  padding: 16,
  zIndex: 1, // Remove if real mint button
}));

const StyledStatusLabel = styled(StatusLabel)(() => ({
  position: 'absolute',
  left: 16,
  top: 16,
  zIndex: 1,
}));

const MintIconButton = styled(IconButton)(() => ({
  position: 'absolute',
  left: 16,
  top: 16,
  zIndex: 1,
  background: 'rgba(0, 0, 0, 0.7)',
  '&:hover': {
    background: 'rgba(128, 58, 254, 0.9)',
  },
}));

const ImageTitle = styled('span')(({ theme }) => ({
  opacity: 0,
  textAlign: 'left',
}));

const ImageBackdrop = styled('span')(({ theme }) => ({
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  backgroundColor: theme.palette.common.black,
  opacity: 0,
  transition: theme.transitions.create('opacity'),
  borderRadius: 32,
}));

const ImageImagine = styled('span')(() => ({
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
  backgroundSize: 'cover',
  backgroundPosition: 'center 40%',
  borderRadius: 32,
}));

const GalleryItem = ({
  imagine,
  imagine: {
    id,
    title,
    status,
    isMyFavorite,
    public: publicStatus,
    context: imgContext,
    thumb_url: imgUrl,
    count_favorites: countFavorites,
  },
  onOpen,
  onClose,
  ...props
}) => {
  const [isHoverFavorite, setHoverFavorite] = useState(false);

  return (
    <>
      <ButtonBase
        className="MuiButtonBase-gallery"
        disableRipple
        focusRipple
        onClick={(event) => onOpen(event, id)}
      >
        <ContextContainer>
          <Box display="flex" justifyContent="space-between">
            <Box
              display="flex"
              visibility={status === IMAGINE_STATUS.COMPLETE && 'hidden'}
            >
              <StyledStatusLabel status={status} />
            </Box>
            {status === IMAGINE_STATUS.COMPLETE && (
              <React.Fragment>
                <Favorite
                  imagineId={id}
                  isMyFavorite={isMyFavorite}
                  isHoverFavorite={isHoverFavorite}
                  isHidden
                  onHoverFavorite={setHoverFavorite}
                  count={countFavorites}
                />
              </React.Fragment>
            )}
          </Box>
          <ImageTitle className="imageTitle">
            <Typography color="textPrimary" variant="subtitle1" noWrap>
              {title}
            </Typography>
            <Box
              display="flex"
              justifyContent="space-between"
              alignItems="center"
            >
              {imgContext && <Label>{imgContext}</Label>}
              <PublicLabel publicStatus={publicStatus} />
            </Box>
          </ImageTitle>
        </ContextContainer>
        <ImageImagine
          style={{
            backgroundImage: `url(${
              imgUrl ?? `${authDomain}/images/glitchcat.gif`
            })`,
          }}
        />
        <ImageBackdrop className="imageBackdrop" />
      </ButtonBase>
    </>
  );
};

export default GalleryItem;

Answer №1

Did you attempt adjusting the height property of the ButtonBase element to height: auto and setting the min-height to min-height: fit-content?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting my AngularJS animations to work, hitting a roadblock

Here is the code I've put together for you to review, with no official purpose in mind. I just saved this code to use at a later time. <script> var apps = angular.module('myApp', ['ngAnimate']); //header apps.cont ...

As I tried running both `npm install --force` and `npm i`, an unexpected error occurred

npm WARN using --force Recommended protections disabled. npm WARN ERESOLVE overriding peer dependency npm WARN While resolving: @material-ui/[email protected] npm WARN Found: [email protected] npm WARN node_modules/react npm WARN react@"^18.2.0" fro ...

When utilizing Material-UI GridListTile within a component in React, the style attributes may be lost

In my UI, I display a <GridList> with custom component tiles that I created. Initially, I was confused about React hooks and prop passing, so I was treating it like a regular JS function: const VideoTile = ({...props}) => { const { url, class ...

The public URL is not being properly configured by the React Builder tool

Attempting to compile my react app using React's build tool is proving to be a challenge. npm run build Upon opening the index.html file in the build directory, all I see is an empty page. This issue stems from the incorrect paths set by the react b ...

Having difficulty transferring navigation props between screens using react-navigation

Within my ContactList component, I have utilized a map to render various items. Each item includes a thumbnail and the desired functionality is that upon clicking on the thumbnail, the user should be directed to a new screen referred to as UserDetailsScree ...

Expansive Carousel Feature with Ng Bootstrap

In my Angular 5 application, I am utilizing the Carousel component from "@ng-bootstrap/ng-bootstrap": "^1.1.2". I am trying to display pictures in full screen but when I press F11, the image appears like this. I am unsure of which CSS properties to apply ...

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

Tips for positioning a label within the span element wpcf7-form-control-wrap

Is it possible to place the label for input elements inside the span element generated by the cf7 shortcode? I want to achieve this in order to make the label only visible when the input field is in focus. To accomplish this, both the label and the input ...

The front end button stubbornly refuses to comply and redirect to another page

I am having trouble getting my button element to redirect my page to another page. I have tried using an onclick function inside the button tag with window.location.href, as well as creating a separate function for the redirect, but nothing seems to be wor ...

The component is not updating accordingly after the action has been dispatched, even though mapStateToProps has

Below is the structure of my reducer: export default function reducer(state={ fetching: false, }, action) { switch (action.type) { case 'LOGIN_REQUEST': { return {...state, fetching: true} } ... return state When I dispatch an ...

Using NextJS with Storybook: The Issue with Optional Chaining

https://i.stack.imgur.com/lY2F1.png rehype-ignore - index.js contains the following code snippet: import { visit } from 'unist-util-visit'; const rehypeIgnore = (options = {}) => { const { openDelimiter = 'rehype:ignore:start', ...

Achieving perfect alignment of an iframe on a webpage

Having an issue with aligning the iframe on my website. I have two buttons set up as onclick events that connect to internal pages displaying PHP data in tables within the iframe. Despite trying various CSS styles and positioning methods, I can't seem ...

Error message stating: "The 'MktoForms2' property is not recognized within the scope of 'Window & typeof globalThis'."

Encountering the following error message: (Property 'MktoForms2' does not exist on type 'Window & typeof globalThis') while working with react and typescript useEffect(() => { window.MktoForms2.loadForm("//app-sj11.marke ...

Why does my anchor appear with a different style compared to my submit button?

I encountered an issue where I have created a submit button and anchor link with the same class name and style, but they are displaying differently. The anchor link appears to be larger than the submit button. You can see the difference in size here: Belo ...

Safari is experiencing issues with overflow-x functionality after a device rotation

I'm currently in the process of developing a website that requires a specific div element to be horizontally scrollable if its content exceeds the screen size. This functionality works smoothly on most browsers, except for Safari: Scenario: When the ...

I'm struggling to make this background show up in a div

Anyone able to help me figure this out? I can't seem to get the achtergrond_homepage.png as a background in rounded corners. Edit: It seems like the gray color is always on top. Could it be controlled in the JavaScript part? This is the CSS: @ch ...

Tips on crafting tailored CSS styling for targeted div elements such as before and after:

Looking to style specific div elements with the same class name? <div class="main"> <div class="banner_image"> banner 1</div> <div class="banner_image ">banner 2</div> <div class="banner_image ">banner 3</di ...

Iterating through a SASS map and retrieving the next item in the loop

I am working with a color array that looks like this: $colors: ( 'primary': '#aaa', 'secondary': '#bbb', 'color-3': '#ccc', 'color-4': '#ddd', 'color-5': & ...

Is the textarea's shape out of the ordinary?

Most textareas are typically rectangular or square in shape, similar to this: However, I am interested in having a custom-shaped textarea, like the example below: Is it feasible to achieve? ...

Is there a way to remove <font> tags using Javascript designMode?

Currently, I am in the process of developing a WYSIWYG editor as a hobby project. My approach involves utilizing an iframe with design mode enabled and leveraging the execcommand feature in JavaScript to implement the editor functionalities. For instance, ...