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

`Creating a union of prop types in TypeScript and React`

I'm facing an issue with a component prop that I need to restrict to specific strings using a union type, as shown below: type HeadingProps = { level?: 'h1' | 'h2' | 'h3' | 'h4'| 'h5' | 'h6&a ...

After encountering an error, the puppeteer promptly shuts down the page

During my page testing, an error is thrown by a dependency. Although the error is not critical and does not impact my application, when testing with Puppeteer and encountering this error, it abruptly closes the tested page. How can I bypass this error to c ...

What is the best way to specify the CSS :hover state within a jQuery selector?

I am trying to change the background color of a div element when hovered using jQuery, but for some reason the following code is not working as expected: $(".myclass:hover div").css("background-color","red"); Can someone provide guidance on how to achiev ...

Conceal content within a bullet point

I'm encountering an issue with this specific element. HTML <div class="navbar slide-menu"> <div class="container"> <ul class="nav navbar-default"> <li class="brand"><a href="#">Menu</a></li> ...

How can we include identical item names within a single JavaScript object?

My attempt at achieving the desired result involves creating an object like this: var obj = {id: id, items: "asdf", items: "sdff", test: varTest}; However, I face a challenge where I need to dynamically add two elements with the same name 'items&apo ...

Unable to locate the JavaScript/jQuery key

Struggling with a dictionary in JavaScript being passed to a function in Django. Despite the key existing, I'm getting an error saying 'key message not found'. As a newbie in Javascript and JQuery, I must have made a simple mistake somewhere ...

The CSS div mysteriously vanishes right before I can trigger the click event

My CSS code looks like this: #searchbar-wrapper input#header-searchbar:focus + #search-dropdown-wrapper { display: block; } The purpose of this code is to make a dropdown visible when a user focuses on a textbox. The default behavior should be th ...

Sending both the minimum and maximum slider values to PHP using POST can be achieved by formatting the data correctly

I am attempting to transmit the minimum and maximum values to PHP using submit through a dual slider bar The static page makes a request to the server-side PHP code <?php include('server/server.php') ?> Below is the JavaScript code ...

Enhancing Image Quality upon Hovering

Is there a way to prevent the content of the article from moving when an image becomes absolutely positioned? The issue I am facing is that the image overlaps its container with overflow: hidden only when the img is absolute positioned. article { back ...

Updating a column in a SQL Table via an Ajax request

I am attempting to store the on or off value from a form into an SQL database by calling a JS function with an AJAX request that sends it to a PHP page for processing. I seem to be facing some issues with my code and could really use some assistance as the ...

Guide to invoking the NPM request multiple times within the mocha before hook

Can anyone advise on the correct way to call request multiple times (2 times) in mocha before hook? I am currently facing an issue where I get an error saying 'done() called too many times'. describe('...', function(){ before(functio ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

Challenges arise with the height settings of ui-grid

Currently, I am facing an issue with using height: auto on an angularJS ui-grid. The problem arises from an inline style that specifies a fixed height on the div to which the ui-grid attribute is added. Additionally, the function getViewPortStyle() dynamic ...

Implementing dynamic checkbox values depending on a selection from a dropdown menu in Angular

In my checkbox list, I have various Samsung mobile models and two offers available. $scope.offers = [ { id: "as23456", Store: "samsung", Offer_message:"1500rs off", modalname: "Samsung Galaxy You ...

Unleashing the power of Material UI Chip component by removing the hover, active, and focus gray color effect

I have Chips implemented in various colors like green, yellow, and blue. The default MUI Chip component comes with a grey hover/active/focus CSS style. I want to remove this grey background color from the MUI Chip component instead of replacing it with ano ...

Verifying the type and quantity of an item

Looking at a piece of code where a specific condition is being checked, I'm curious to know why someone might want to skip this particular condition. var number = /^\d+/; var type = Object.prototype.toString.call(obj); for(var key i ...

Unable to Submit Form in JSP Page

I have encountered an issue with a JSP page that contains a form which I am submitting using JavaScript. When the page has a smaller number of items, between 10-50, the submission works perfectly fine. However, when there are around 500 items or more on t ...

Listening for keypress events on a div element using React

I'm currently struggling with implementing a keypress listener on a component. My goal is to have my listener activated whenever the "ESC" key is pressed, but I can't seem to figure it out. The function component I am working with is quite stra ...

Incomplete Json information

As I embark on my journey to learn Javascript and work on building an application simultaneously, I can't help but feel optimistic about the learning process. To guide me through this venture, I've turned to the teachings of Alex MacCaw in his bo ...

Passing React props to a component is essential for proper functioning

The following code represents a react component named Start. Its main purpose is to receive a player's name through a form using onSubmit. The player's name is stored in a hook called "player" and then passed as a prop to another component called ...