How can I use CSS to ensure that both cards and images are equal in size?

I am currently utilizing react, with Material-ui being used for the Cards. For the layout, I have implemented CSS Grid Layout for the Grid system. Presently, the structure looks like this:

https://i.stack.imgur.com/0FDyY.png

However, my desired outcome is more along the lines of:

https://i.stack.imgur.com/Ue2TW.png

Yet, there are two main issues I am facing:

  1. I intend to make all the cards uniform in height (415px). Despite trying to set the height to 415px on .BeerListingScroll-info-box, it does not seem to take effect.

  2. The images of bottles and kegs differ in size [keg (80px x 160px) vs. bottle (80px x 317px)]. Is there a way to render them at a more similar size?

-

Code:

BeerListingScroll

import React, { Component } from 'react';
import ReduxLazyScroll from 'redux-lazy-scroll';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchBeers } from '../../actions/';

import BeersListItem from '../../components/BeersListItem';
import ProgressIndicator from '../../components/ProgressIndicator';

import './style.css';

class BeerListingScroll extends Component {
  constructor(props) {
    super(props);

    this.loadBeers = this.loadBeers.bind(this);
  }

  loadBeers() {
    const { skip, limit } = this.props.beers;
    this.props.fetchBeers(skip, limit);
  }

  render() {
    const { beersArray, isFetching, errorMessage, hasMore } = this.props.beers;
    return (
      <div className="container beers-lazy-scroll">
        <ReduxLazyScroll
          isFetching={isFetching}
          errorMessage={errorMessage}
          loadMore={this.loadBeers}
          hasMore={hasMore}
        >
          <div className="BeerListingScroll-wrapper">
            {beersArray.map(beer => (
              <div key={beer.id} className="BeerListingScroll-info-box">
                <BeersListItem beer={beer} />
              </div>
            ))}
          </div>
        </ReduxLazyScroll>
        <div className="row beers-lazy-scroll__messages">
          {isFetching && (
            <div className="alert alert-info">
              <ProgressIndicator />
            </div>
          )}

          {!hasMore &&
            !errorMessage && (
              <div className="alert alert-success">
                All the beers have been loaded successfully.
              </div>
            )}
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    beers: state.beers,
  };
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchBeers }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(BeerListingScroll);

BeerListingScroll css

.BeerListingScroll-wrapper {
  display: grid;
  margin: 0;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr) ) ;
  background-color: #f7f7f7;
}

.BeerListingScroll-info-box {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
  width: 320px;
}


/* This applies from 600px onwards */
@media (min-width: 1820px) {
  .BeerListingScroll-wrapper {
    margin: 0 400px;
  }
}

@media (min-width: 1620px) {
  .BeerListingScroll-wrapper {
    margin: 0 300px;
  }
}

@media (min-width: 1366px) {
  .BeerListingScroll-wrapper {
    margin: 0 200px;
  }
}

BeerListItem serves as the child component of BeerListingScroll

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

function BeerListItem(props) {
  return (
    <div>
      <Card raised>
        <CardContent>
          <img src={props.beer.image_url} alt="beer" width="30%" />
          <Typography variant="headline" component="h2">
            {props.beer.name}
          </Typography>
          <Typography component="p">{props.beer.tagline}</Typography>
        </CardContent>
      </Card>
    </div>
  );
}

export default BeerListItem;

Complete project details can be found on github -> Github

Answer №1

I recently found a solution for managing image sizes on this topic here.

After implementing the advice, I made the following adjustments:

.BeerListItem-img {
  height: auto;
  max-height: 250px;
  width: auto;
  max-width: 250px;
}

To adjust the card size, I simply added the following code within the BeerListItem class to reference the Card component (.BeerListItem-main-card):

function BeerListItem(props) {
  return (
    <div>
      <Card raised className="BeerListItem-main-card">
        <CardContent>
          <img
            src={props.beer.image_url}
            alt="beer"
            className="BeerListItem-img"
          />
          <Typography variant="headline" component="h2">
            {props.beer.name}
          </Typography>
          <Typography component="p">{props.beer.tagline}</Typography>
        </CardContent>
      </Card>
    </div>
  );
}

Additionally, here is the corresponding CSS specific to that component.

.BeerListItem-main-card {
  width: 320px;
  height: 415px;
}

.BeerListItem-img {
  height: auto;
  max-height: 250px;
  width: auto;
  max-width: 250px;
}

By making these two changes, I successfully achieved my desired outcome.

Answer №2

If you're looking to improve your layout, consider using the display:flex; property.

Check out this amazing code pen that could assist you in achieving your desired outcome:

https://codepen.io/enxaneta/full/adLPwv

For a more specific example tailored to your needs, take a look at this demo I've put together:

https://jsfiddle.net/dalecarslaw/sxdr3eep/

Focus on these key areas of code for implementing the desired layout:

  display:flex;
  align-items:space-between;
  justify-content:space-between;
  flex-wrap:wrap;

Answer №3

To ensure uniformity in card sizes, I recommend implementing the "flex:1" property to the parent element of the cards using display flex. This adjustment will automatically adjust the size of each child element, including images, creating a consistent layout.

By applying this solution, the issue was resolved successfully.

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

Discovering the specific marker that was clicked from a group of Google map markers

I have a collection of marker objects named markers. I am currently utilizing a for loop to assign event listeners to each one. However, I am encountering difficulty in determining which specific marker was clicked. This is the current code snippet I have ...

Adding a button to the right of a text-field input in Vuetify app

I need advice on the best way to use Vuetify in order to display a button to the right of a text-field (attached). I've checked the main site for information but couldn't find anything related to this specific scenario. <v-row clas ...

Steps for inserting a button within a table

Currently, I have implemented a function that dynamically adds the appropriate number of cells to the bottom of my table when a button is clicked. This is the JavaScript code for adding a row: <a href="javascript:myFunction();" title="addRow" class= ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

What are the best techniques for organizing SCSS in Next.js?

There are multiple pages with some unused items. Is there a method to search and delete all the items based on their classname? Appreciate any assistance you can provide! ...

Is there a way to specifically execute a Mongoose validate function solely for the create user page and not the edit user page?

Exploring Different Tools In the process of developing a website using Node.js, Express, and MongoDB. Leveraging mongoose for interacting with the MongoDB server has been quite beneficial. However, I encountered an issue where a function within my Mongo ...

Netlify is failing to recognize redirect attempts for a Next.js application

After successfully converting a react site to utilize next.js for improved SEO, the only hiccup I encountered was with rendering index.js. To work around this, I relocated all the code from index to url.com/home and set up a redirect from url.com to url.co ...

Organizing content into individual Div containers with the help of AngularJS

As someone who is new to the world of AngularJS, I am currently in the process of learning the basics. My goal is to organize a JSON file into 4 or 5 separate parent divs based on a value within the JSON data, and then populate these divs with the correspo ...

Exploring Nested Views in a MEAN Application using UI Router

I am currently developing a MEAN application and struggling to get my ui-router functioning correctly. Within my index.html template, I have loaded all the necessary javascript and css for my application such as angular, jquery, angular-ui-x, bootstrap. I ...

Unhandled error: 'this' is not defined within the subclass

My code snippet is causing an issue when run in Node v4.2.4: "use strict"; class Node { constructor() { } } class Person extends Node { constructor() { } } const fred = new Person(); Upon running the code, I encounter the following error mes ...

What is the best way to send an array of objects to a Jade template?

I'm looking to retrieve an array of objects from MongoDB and pass it to the client... Here is an example object: var objeto_img= { name:'name of the file', ...

The Javascript eval method throws a ReferenceError when the variable is not defined

In my constructor, I was trying to create a dynamic variable from a string. Everything was working smoothly until I suddenly encountered this error out of nowhere. I didn't make any changes that could potentially disrupt the system, and the variables ...

The language selection feature is not appearing on the Safari Version 14.1.2 browser

Within the application I am developing, the language picker appears correctly in every browser. At the top of the screen, users have the option to select their preferred language for the app. However, when tested on Safari, the language picker does not ap ...

Converting units to rem dynamically in CSS: a comprehensive guide

Hey there, I'm currently trying to dynamically convert units into rem in CSS and facing some issues. I have set the root font-size as 23px The current font-size is 16px The expected result should be 16 / 23 => 0.695rem Question: I am looking for ...

Tips on avoiding a page reload following a form submission using JQuery

Currently developing a website for my app development project, I've encountered an unusual issue. Utilizing some JQuery to transfer form data to a php page called 'process.php' and then add it to my database. The strange part is that the pa ...

Tips for passing an array between components in Angular 2

My goal is to create a to-do list with multiple components. Initially, I have 2 components and plan to add more later. I will be sharing an array of tasks using the Tache class. Navbar Component import { Component } from '@angular/core'; impor ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

The compatibility between Babel 7 and the preset-es2015 is not very reliable

After reading this useful tutorial on implementing server-side rendering with create-react-app, I attempted to execute the following code snippet: require('ignore-styles'); require('babel-register')({ ignore: [/(node_modules)/], ...

Declaring global types in a NX and NextJS monorepository for enhanced development consistency

I've been searching online to find a good solution for my issue, but so far I haven't had any luck. Currently, I have a NX monorepo with NextJS and I'm attempting to create a global types/ folder that can be accessed by all my apps and libs ...

Transform the text upon hovering over the image, with the text positioned separate from the image

I'm looking for a solution where hovering over images in a grid area will change the text on the left side of the screen to display a predefined description of that image. I've been working on this problem for hours and would appreciate any help. ...