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

What could be causing the failure of this web component using shadow DOM when the HTML code includes multiple instances of the component?

Recently, a question was raised on this platform regarding the use of Selenium to access the shadow DOM. Curious about this topic, I delved into the MDN article Using shadow DOM and decided to replicate the code on my local machine. Surprisingly, it worked ...

Decode my location and input the address before validating it

While I have come across numerous plugins that enable geolocation and display it on a map, I am searching for something unique. I am interested in implementing geocoding when a user visits the page with an option to "allow geolocation." If the user agrees ...

The enchanting world of CSS background scrolling animations

I am currently developing a website where I have split the hero/header into two sections - one on the left with information and the other on the right with a graphic. I wanted to add a simple parallax effect to the image on the right side, so I used backgr ...

Trouble encountered when utilizing jQuery for XML to HTML conversion and vice versa (CDATA mistakenly transformed into HTML comments)

I am in the process of developing a plugin/bookmarklet that is designed to extract an XML document from the <textarea> element on a web page, make modifications to the XML content, and then reinsert the updated version back into the <textarea> ...

Ensures that two divs have the same dimensions

Currently, I have a line of sections set up like this: I am attempting to ensure that the second div matches the height of the first one, despite the fact that their heights are determined by the size of the pictures which may vary. Do you have any sugges ...

Adjust the x-scroll to continue infinitely while deactivating the y-scroll

Is there a method in CSS to prevent vertical scrolling and have all the contents of a div positioned next to each other so that they extend beyond the visible browser window? I would like to enable horizontal scrolling to bring them back into view. How c ...

The function TagBuilder.MergeAttributes is malfunctioning

My attempt at creating a custom helper in MVC is not working as expected. The custom attributes are not being added to the HTML: Custom Helper Function public static MvcHtmlString MenuItem(this HtmlHelper helper, string linkText, string actionName, strin ...

Responsive design with Semantic UI

Can you please provide an example of how to design for different screen sizes using Semantic UI instead of Bootstrap? I'm looking for something similar to Bootstrap's sm and lg classes. For instance, would it look like this: <div class="col s ...

Is there a way for me to upload a csv file along with a password_hash

I have successfully implemented this code on my website, allowing me to upload CSV files to my database. However, I am looking to enhance the security measures by changing $item2 from a numerical password to a password_hash. ($data[1] currently represent ...

Is your webpage displaying unnecessary white space on smaller screens?

.main { background: linear-gradient(-45deg, #ee7752, #e73c7e, #23a6d5, #23d5ab); background-size: 400% 400%; animation: gradient 15s ease infinite; height: 100vh; min-width: 100%; width: 100%; overflow-x: hidden; overflow: hidden; } Here i ...

Struggling to make `align-items="baseline"` function properly

I'm encountering an issue with alignment in my sandbox project. Specifically, I want the bottom of texts with different font sizes to be on the same y axis but I can't seem to figure out how to make it happen. Check out this picture to see exact ...

Implement input validation in React by enhancing the functionality of HTML input tags

Below is the input provided: const REGEX_EMAIL_VALIDATION = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}&bsol ...

Distance between cursor and the conclusion of the text (autofocus)

I discovered a method to automatically position the cursor at the end of a string using autofocus: <input name="adtitle" type="text" id="adtitle" value="Some value" autofocus="" onfocus="this.setSelectionRange(this.value.length,this.value.length);"> ...

Steps for creating a square button

Is it possible to create a square button on my website that still functions like a traditional button? I want the button to change appearance slightly when scrolled over. Currently, I have an example where the button is not clickable: http://jsfiddle.net ...

Code snippet in Python using Selenium where Google Maps is not visible in the page source

Currently, I am attempting to extract GPS coordinates data from a property listing: https://www.primelocation.com/new-homes/details/55357965?search_identifier=d10d089a335cc707245fb6c924bafbd2 The specific GPS coordinates can be found on the "Map & Nearby" ...

Using CSS, the ability to scroll to the top of a page is restricted when an inner div expands to the top while using flex

While following a tutorial on YouTube, I encountered an issue where my expanding content, when exceeding the size of the window in a small screen view, prevented me from scrolling to the top. Interestingly, I could scroll to the bottom and back up to that ...

Guide to designing a dropdown navigation menu in GWT

Hey, I'm currently working on setting up a drop down menu using GWT and here's the layout I have in mind: | Categories | Pictures | Other | When the categories dropdown opens, my goal is to display the categories grouped in pairs. For example: ...

Utilizing the hcSticky plugin for creating a scrolling effect on webpage content

I'm attempting to utilize the JQuery plugin, hcSticky, in order to achieve a scrolling effect on my fixed content. However, I seem to be encountering some difficulty getting it to function properly. What could I possibly be doing incorrectly? JSFIDDL ...

Using JAVA to generate SVG images, then embedding them into HTML using Base64 encoding URI

I am currently developing a service to generate SVG images. The main criteria is that the generated SVG must be compatible with an img tag (with the added bonus of working in a script tag) and it needs to function without the use of JavaScript. After some ...

Struggling to link an external JavaScript file to your HTML document?

While attempting to run a firebase app locally, I encountered an error in the chrome console: GET http://localhost:5000/behaviors/signup.js net::ERR_ABORTED 404 (Not Found) Do I need to set firebase.json source and destination under rewrites or add a rout ...