What is the best approach for scaling @material-ui Skeleton in a grid row with variable heights?

I am working on creating a grid of Avatar images with a transition state where I want to show a skeleton representation of the image. To achieve this, I am using @material-ui/lab/Skeleton.

The issue I'm facing is that since my images are set to autoscale within a grid using height: auto, width: 100%, and the height/length of the content displayed below the image varies, there is no fixed height value that I can pass to the skeleton component.

You can observe the problem when you resize the width of the sandbox screen. The height of the grid item increases, causing the circular skeleton to start deforming into an oval shape.

Is there a solution that can give me behavior similar to setting the image's height: auto, width: 100%?

You can view the full code I have so far below and in the sandbox here: https://codesandbox.io/s/skeleton-scaling-y00cd.

// Full revised source code goes here. Keep all the contents as it is.

Answer №1

The solution provided below is based on the information found in this article: https://css-tricks.com/aspect-ratio-boxes/#article-header-id-3

Essentially, the approach involves using percentage-based padding-top to create a box with a specific aspect ratio, such as a square. When specifying padding-top or padding-bottom in percentages, it is crucial to remember that it is based on width, resulting in a height equivalent to the specified width.

The relevant CSS/JS snippet is as follows:

  avatarSkeletonContainer: {
    height: 0,
    overflow: "hidden",
    paddingTop: "100%",
    position: "relative"
  },
  avatarLoader: {
    position: "absolute",
    top: 0,
    left: 0,
    width: "100%",
    height: "100%"
  },

This code segment is then utilized in the following manner:

<Grid container item xs={3} spacing={0} direction="column">
          <div className={classes.avatarSkeletonContainer}>
            <Skeleton variant="circle" className={classes.avatarLoader} />
          </div>
          <Skeleton className={clsx(classes.titleLoader, classes.title)} />
          <Skeleton className={clsx(classes.contentLoader, classes.content)} />
        </Grid>

Here's my modified version of your sandbox code:

// The complete code can be found here
// Link: https://codesandbox.io/s/skeleton-scaling-ndzs7?fontsize=14&hidenavigation=1&theme=dark
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Avatar from "@material-ui/core/Avatar";
import Skeleton from "@material-ui/lab/Skeleton";
import Typography from "@material-ui/core/Typography";
import clsx from "clsx";
import Grid from "@material-ui/core/Grid";

const useStyles = makeStyles(theme => ({
  // Styles and classes definition go here
}));

export default function ImageAvatars() {
  const classes = useStyles();

  return (
    <div className={classes.root}>
      // Nested grid structure and components are implemented here
    </div>
  );
}

If you need further assistance or clarification, feel free to ask!

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

Change the dimensions of a picture from 4:3 to 16:9 while maintaining its responsiveness using CSS

Imagine I have this image with a 4:3 aspect ratio and dimensions of 640x480: https://i.sstatic.net/p4xRM.jpg Here is the code used to display it: <img src="../static/images/image4-3.jpg" class="img-fluid" alt=""> Now ...

Creating an easy-to-update catalog utilizing an external file: A step-by-step guide

I am looking to create a product catalog with 1-4 products in a row, each displayed in a box with details and prices. I would like to be able to generate the catalog easily using an XML/CSV file that can be updated. Can anyone provide guidance on how to ac ...

Images that adjust to different screen sizes within a grid layout

I have four images that need to be aligned in the following layout: ____________ |1 |4 | |_____| | |2 |3| | |__|__|______| They must be flush against each other, occupy 100% of the viewport's width, and most importantly, be respon ...

Display a horizontal progression indicator during the page download process

Occasionally, website pages may take a while to download without the user even realizing it. This can be problematic if the user clicks on an image or button with an event handler attached, as it may break the page functionality. To address this issue, I ...

Help needed with CSS menu dropdown problem

Hello everyone, I am currently working on creating a menu for the top navigation of my website. My goal is to have a list of items appear below the menu when hovering over it with the mouse. Right now, I am testing this on a local HTML file before impleme ...

Troubleshooting React Native Expo Image Picker Glitches

Whenever I attempt to add a plugin ("plugins": [ [ "expo-image-picker", { "cameraPermission": "The app accesses your camera to let you add new places" } ] ]), I encounter an error related to the plugin. Then, when I ...

Guide to retrieving a .txt file from a separate domain using server-side JavaScript and transferring it to the client side

My goal is to retrieve a .txt file from a web server on a different domain that does not have CORS or web services enabled. I believe I will need to handle this task on the server side using Node.js and JQuery, but I am unsure of where to begin. Currently, ...

Looking to set the "min" attribute for an input type="date" in HTML5 with a specific date format preselected?

My upcoming date has a specific format as detailed below. Date_received = Tue Apr 05 2016 00:00:00 GMT+0530 (India Standard Time) To set the 'min' attribute for the HTML5 input type="date" datepicker, I need to initialize it using the following ...

Can we set $_SESSION equal to $_POST data?

I'm not sure if I'm on the right track, but let's consider this scenario. form.php <?php session_start(); $_SESSION['average'] = $num; echo ' <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN"> <h ...

When attempting to perform conditional rendering in React using a stateless functional component, I encounter an error stating "Unexpected token, expected ,"

Here is the code snippet: 'use strict' import React from 'react' import { connect } from 'react-redux' import { Panel, Col, Row, Well, Button } from 'react-bootstrap' const Cart = ({ cart }) => { const cartI ...

EJS Templates with Node.js: Embracing Dynamic Design

Is there a way to dynamically include templates in EJS without knowing the exact file name until runtime? The current EJS includes only allow for specifying the exact template name. Scenario: I have an article layout and the actual article content is stor ...

Error in Prisma: Unable to retrieve data due to undefined properties (attempting to access 'findMany')

Recently, I've been working on a dashboard app using Prisma, Next.js, and supabase. Encountering an issue with the EventChart model in schema.prisma, I decided to create a new model called EventAreaChart. However, after migrating and attempting to ex ...

The URL redirect is malfunctioning and prompting an error stating "No 'Access-Control-Allow-Origin' header"

Having trouble sending an Ajax request to a Node.js server from my application and encountering the following error: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the ...

NodeJs guide on removing multiple documents from a MongoDB collection using their _id values

Consider the following array of _ids: ["a12s", "33qq", "121a"] In MongoDB, there are methods such as deleteMany, which allows deletion based on specific queries: var myquery = { address: 'abc' }; dbo.collection("customers").deleteMany(myque ...

Karma, Webpack, and AngularJS are successfully passing all tests, yet encountering karma errors with an exit code of 1

Currently running karma 4.0.1, webpack 4.31.0, angular 1.6.8, karma-jasmine 2.0.1, jasmine-core 3.4.0 Recently at my workplace, I transitioned our angularjs application from a traditional gulp build process to webpack + es6. The journey has been smooth wi ...

To demonstrate movement through both revealing and concealing

Currently, I am working on an assignment that involves rotating an image on hover. My task is to rotate the image first, then animate another object once the image rotation is complete. Upon mouse out, the initial image should return to its original positi ...

Is there a way to efficiently access checkboxes by their IDs and toggle classes without the need for redundant classes and functions?

In my current project, I have set up functionality to toggle classes on a table for hiding specific columns. This is determined by checkboxes selected by the user above the table, each checkbox having its own unique ID like "product_1", "product_2", and so ...

Running a child process in the browser using Node.js with the help of browserify

Utilizing browserify to enable node.js functionality in the browser, I am attempting to run a child process in my index.js file: var exec = require('child_process').exec; //Checking the installed node version var ls = exec('node -v', f ...

When attempting to send data using jQuery to PHP, an issue arises where PHP is unable to receive the information, resulting in an undefined variable

Has anyone successfully sent data from an HTML select to a PHP file using jQuery? I've tried multiple solutions suggested here, but none seem to be working for me. Below is the code I'm using: <select id="city" name="city" > <optgro ...

What is the best way to include a new user in the memory database when there is no database or storage back-end?

During an online test, I was given the task of adding a user to a database stored in memory. The request body required JSON formatting as shown below: { "id": "aabbbccddeeefff", "name": "User One", "hobbies": [ "swim", "sing", "workout" ] } (Users ...