Displaying cards horizontally on desktop and vertically on mobile using CSS

Context and Issue

I am currently working on this specific page, with a focus on the "Top Artists" section.

  • Desired Outcome:

    • When viewed from a laptop, I aim for the cards to be displayed as vertical rectangles, where the ranking is at the top, followed by the image in the middle, and the artist's name at the bottom. These cards should have the same width and height, aligned horizontally with the "#1" card on the left and the "#5" card on the right.
    • For mobile devices, my goal is to have the cards appear as horizontal rectangles, with the ranking on the left, image in the center, and artist name on the right. Similar to the laptop view, these cards should share the same measurements.
  • Current Outcome: At present, the layout seems to match my laptop expectations (except for the placement of the "Top Artists" title). However, on mobile, the cards display varying widths.

Supporting Information

This is how it currently appears on a laptop:

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

And this is the current appearance on a mobile device:

https://i.stack.imgur.com/iON4Jm.jpg

Code Snippet

Here is the CSS code within my <style></style> tags:

.top-artists {
    /* CSS rules */
}

/* Additional CSS styles */

@media (max-width: 500px) {
    /* Responsive styles for smaller screens */
}

Below is the snippet responsible for creating the artist cards:

 <!-- HTML code snippet goes here --> 

Implementing Suggestions

Following advice provided by other users, I made changes within the @media rule, but did not achieve the desired outcome. Here's a screenshot showcasing the result:

https://i.stack.imgur.com/DsUi8m.jpg

Another suggestion was to use width:100% within the @media query, resulting in all cards being of equal size but vertically oriented. My preference, however, is to have them arranged horizontally. Here's a glimpse with width:100% applied:

https://i.stack.imgur.com/8CQvZm.jpg

Answer №1

If you want to ensure the cards have a consistent width on mobile devices, simply include it in the CSS under the .artist-card class.

Another recommendation would be to assign a fixed width to .artist-rank on mobile screens to prevent size fluctuations between single-digit and double-digit ranks.

.top-artists {
    text-align: center;
    margin-top: 30px;
    display: flex; 
    flex-wrap: wrap;
    justify-content: center;
}

.artist-card {
    display: inline-block;
    margin: 20px;
    padding: 10px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s;
    flex: 1;
}

.artist-card:hover {
    transform: scale(1.05);
}

.artist-image img {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #1DB954;
}

.artist-info h3 {
    margin: 10px 0;
    font-size: 16px;
    font-weight: bold;
    color: #333;
}

.artist-rank {
    font-size: 20px; 
    font-family: 'Gotham', sans-serif; 
    color: #1DB954; 
    margin-right: 10px; 
    font-weight: bold;
    margin-bottom: 10px;
}

.artist-name {
    font-size: 18px; 
    font-family: 'Gotham', sans-serif; 
    color: #000;
    margin-top: 10px;
    font-weight: bold;
}

.top-artists-container {
    text-align: center;
}

@media (max-width: 500px) {
    .top-artists {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .artist-card {
        margin: 10px 0; 
        display: flex; 
        justify-content: space-evenly;
        flex: 1;
        width: 90%;
    }
    .artist-image {
        flex: 0 0 100px; 
        margin-right: 10px;
    }
    .artist-name {
        flex-grow: 1; 
        font-size: 18px;
        font-family: 'Gotham', sans-serif;
        color: #000;
        font-weight: bold;
    }
  .artist-rank {
        width: 30px;
    }
}
<div class="top-artists-container">
  <h2 class="section-title">Top Artists</h2>
    <div class="top-artists" style="margin-bottom: 30px;">
        
      
        <div class="artist-card">
            <!-- Get the artist image URL from the dictionary using the artist's name as the key -->
            
            <div class="artist-rank">#1</div>
            <div class="artist-image">
                <!-- Use the artist_image_url obtained from the dictionary -->
                <img src="https://www.gravatar.com/avatar/400b4f31f95b6eb3d6e58671f29e67b2?s=64&d=identicon&r=PG&f=y&so-version=2" alt="Artist Image">
            </div>
            <div class="artist-name">Great artist</div>
        </div>
        <div class="artist-card">
            <!-- Get the artist image URL from the dictionary using the artist's name as the key -->
            
            <div class="artist-rank">#12</div>
            <div class="artist-image">
                <!-- Use the artist_image_url obtained from the dictionary -->
                <img src="https://www.gravatar.com/avatar/400b4f31f95b6eb3d6e58671f29e67b2?s=64&d=identicon&r=PG&f=y&so-version=2" alt="Artist Image">
            </div>
            <div class="artist-name">Good artist</div>
        </div>
        
    </div>
</div>

Answer №2

To utilize flex properly, it is essential to combine flex-basis:auto and flex:1. This combination ensures that the element takes up the entire width, as flex:1 only determines the proportion relative to other children without specifying a base.

Alternatively, you can also include width:100% in the existing code to forcefully fill up 100% of the available space;

Answer №3

Make sure to adjust the width to be 100% for your cards within the designated @media in order to ensure proper display. Here's an example:

@media (max-width: 500px) {
    // ...
    .artist-card {
        width: 100%;
        // ...
    }
}

Answer №4

Make sure to apply this to the parent container.

.parent-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
 }

To find out more, check out this resource here

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

Ways to apply distinct styles to various ids and common classes

When dealing with multiple IDs such as id1, id2, and id3 that share common classes like .selectize-input and .select-dropdown, it can become cumbersome to set styles individually for each ID. Instead of writing: #id1 .selectize-input, #id2 .selectize-inp ...

Showing user data in a div using JavaScript ajax without the use of jQuery

Recently diving into the world of javascript and ajax, I find myself tinkering with code on jsfiddle. My current goal is to populate a list with usernames and emails upon form submission. Upon submitting the form, an error message pops up: {"error":"key m ...

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

Steps to eliminate validation following the clearing of input fields

This is the code I've written for live validation using AJAX in an input field. My issue is that I want the validation to be removed if all inputs are deleted. <script type="text/javascript"> $(document).ready(function(){ ...

Adjust the font size based on the dimensions of the container

I'm currently working on a script that dynamically sets the font-size based on the container's dimensions and the length of the text. This is what I have implemented so far. window.onload = function () { var defaultDimensions = 300; ...

How can we stop the jumping of images in the grid? Is there a way to eliminate the jump effect?

Here is a script I am working with: <script src="http://static.tumblr.com/mviqmwg/XyYn59y3a/jquery.photoset-grid.min.js"></script> <script> $(document).ready(function() { $('.photoset-grid').photose ...

What is the process for altering the background color in this html5up template?

I am struggling to change the brown background color on my website. Despite updating various color values in the CSS file such as'backgroundcolor', I seem unable to make any changes. I have tried altering multiple color entries, but nothing seems ...

jQuery Summation: A Step-by-Step Guide

Hello everyone, I am a new member of this forum and I am looking forward to learning and contributing with all of you. I have encountered a problem that I tried to solve on my own but couldn't figure it out. Would anyone be able to lend me a hand? H ...

How can I restrict the number of items displayed in each row within a navigation submenu flexbox?

My primary navigation menu has numerous child items, and I want to ensure they remain visually appealing and organized. To achieve this, I am aiming to limit each row of submenu items to only 4. After researching other solutions online, I attempted adding ...

What is the best way to customize the appearance of only one of two identical tables using HTML and CSS?

I have two tables that look identical: <html> <head> <style> td, th { text-align: left; padding: 28px; } </style> </head> <body> <table> <tr> ...

Javascript is not functioning properly when making an ajax call

Having a bit of trouble with JavaScript not working after an Ajax call. Everything functions normally until new data is fetched from the database or an Ajax call is made. The issue seems to be that the JavaScript doesn't load properly. Any help would ...

Loop through a list of form names using ng-repeat and send each form name to a JavaScript function when clicked

I have multiple forms within an ng-repeat loop, each with a different name. I need to pass the form data when a button inside the form is clicked. However, when I try to call it like this: checkSaveDisable(updateProductSale_{{productIndex}}) it thro ...

What is the process for updating a collection in MongoDB database with PHP?

After writing a code snippet to gather user input through a form and update a collection based on the entered product ID, I am encountering issues with incorrect results. It seems that I am unable to fetch the correct product ID value, which is causing t ...

Is it possible to utilize a JS script generated within the body or head of an HTML file directly within CSS code?

As a beginner in webpage development, I have a query regarding the technical aspect. Is it possible to utilize variables from a JavaScript function, which is placed either in the head or body of an HTML file, directly in CSS code to make modifications such ...

What is the best way to adjust a CSS width using the output from a JavaScript function?

I am facing a challenge with a GridView within a div wrapper. The row headers along the left side need to always be visible. So far, this setup is working fine. However, I need the wrapper to have a variable width to adjust to the browser size. Although I ...

What is the best way to link and store invoice formset with the main form foreign key in Django?

I am new to Django and need help. I am trying to save my invoice in a database, but the issue I'm facing is that I can't retrieve the foreign key from the main form when I try to save the formset. View.py def createInvoice(request):` if requ ...

Manipulate container (div) to reveal and conceal

My jQuery was working fine until I added some more divs to my HTML. I'm now trying to toggle the opening and closing of a discussion container named discussionContainer with a click on the button replyButton. Any assistance would be highly appreciated ...

Angular version 6 allows for specifying input types as numbers and displaying two decimal digits after the comma

How can I format user input to display as currency with thousand separators in Angular? <input type="number" (ngModelChange)="calculateSum()" (change)="calculateAmount(invoiceQuota)" [ngModel]="invoiceQuota.controls.grossAmount.value"> I have attem ...

Achieve centered alignment for a website with floated elements while displaying the complete container background color

I am currently working on a website that consists of the basic elements like Container, Header, Content, and Footer. The container has a background-color that should cover the entire content of the site, including the header, content, and footer. However, ...

When buttons are clicked within Angular Material's Card component, it automatically triggers the click event of the card itself

One of the challenges I'm facing is having a mat-card within a component template: <mat-card *ngFor="let p of products" (click)="viewProduct(p)"> <mat-card-actions> <button mat-stroked-button (click)="addProductToCart(p)"&g ...