``Troubleshooting Problem with Tailwind's Flex Box Responsive Grid and Card Elements

Starting point:

Preview

https://i.sstatic.net/zfzBU.jpg

Code :

<div class="container my-12 mx-auto">
            <div className="flex flex-wrap ">
              {error ? <p>{error.message}</p> : null}
              {!isLoading ? (
                users.map(user => {
                  const { username, name, email } = user;
                  return (
                    <div
                      key={username}
                      className="w-full md:w-1/2 lg:w-1/3  my-5"
                    >
                      <article class="overflow-hidden rounded-lg shadow-lg">
                        <img
                          alt="Placeholder"
                          className="block h-auto w-full"
                          src="https://picsum.photos/600/400/?random"
                        />
                        <header class="flex items-center justify-between leading-tight p-2 bg-white invisible lg:visible">
                          <h1 class="text-lg">{name}</h1>
                          <p class="text-grey-darker text-sm">
                            {email}
                          </p>
                        </header>
                      </article>
                    </div>

I then attempted to format the code as shown in this CodePen example: https://codepen.io/codetimeio/pen/RYMEJe

However, every time I try to add padding and margin, it moves to the next line, and I am unsure why or how to prevent it.

https://i.sstatic.net/FvQsj.jpg

Here is the updated line of code:

<div key={username} className="w-full md:w-1/2 lg:w-1/3  my-5 mx-5">

This is my Tailwind config file:

module.exports = {
  theme: {
    container: {
      center: true
    },
    screens: {
      sm: "640px",
      md: "768px",
      lg: "1024px",
      xl: "1280px"
    },
    fontFamily: {
      display: ["Gilroy", "sans-serif"],
      body: ["Graphik", "sans-serif"]
    },
    extend: {}
  },
  variants: {},
  plugins: []
};

I am eager to understand what I am doing wrong so that I can effectively use Tailwind as my primary templating framework.


Here is the updated code based on the provided answer:

<div class="container my-12 mx-auto bg-gray-400">
            <div className="flex flex-wrap ">
              {error ? <p>{error.message}</p> : null}
              {!isLoading ? (
                users.map(user => {
                  const { username, name, email } = user;
                  return (
                    <div key={username} className="w-full p-5 md:w-1/2 lg:w-1/3">
                      <article className="overflow-hidden rounded-lg shadow-lg">
                        <img alt="Placeholder" className="w-full" src="https://picsum.photos/600/400/?random" />
                        <header className="flex items-center justify-between leading-tight p-2 bg-white">
                          <h1 className="text-lg">{name}</h1>
                          <p className="text-grey-darker text-sm">
                            {email}
                          </p>
                        </header>
                      </article>
                    </div>

Answer №1

The reason for this issue is the additional margins, when using w-1/3 which translates to approximately width: 33.3333%, adding a margin on top of it causes three elements to not fit in one line.

There are other approaches (considering gutter widths or utilizing the gap property), but in this specific scenario, you can simply opt to use padding instead of margins since there is already a presentational wrapping element around your cards.

For reference, please see this example: https://codepen.io/tlgreg/pen/RmLMOx

Not directly related, but here are some observations based on your code:

  • If you do not utilize the old color palette in the configuration, grey-darker will not function properly.
  • img defaults to block in v1.
  • invisible and lg:visible alter visibility; if the header taking up space is not desired, consider using hidden and lg:flex.

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

A TypeError is thrown when attempting to use window[functionName] as a function

I came across this page discussing how to call a function from a string. The page suggests using window[functionName](params) for better performance, and provides an example: var strFun = "someFunction"; var strParam = "this is the parameter"; //Creating ...

Enhance your Zara shopping experience with the dynamic image zoom-in

I am currently exploring ways to replicate the image zoom-in feature seen on Zara's product pages. To see this effect in action, visit their site: Upon clicking on the image, it opens up in a popup window where it is enlarged to fit the entire screen ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

Is axios allowed to be used in this scenario?

As a newcomer to web development, I apologize in advance if my question seems basic or if the details provided are insufficient. Nevertheless, I hope you can assist me with the following query: Is it possible to execute an axios.post request within a vue. ...

When I set my header as "fixed", it automatically adjusts the size of the header box

Looking to create a fixed-header that includes clickable links on the left and our logo on the right. Encountering an issue when trying to make the header take up the full width of the screen in its fixed position. The header's width seems to shrink ...

The specified 'Promise<Modules>' type argument cannot be assigned to the parameter of type '(params: any) => Promise<Modules>' in the current context

Looking for some help with this helper function that I need to call, it has the following signature: export const fetchPaginated = async <T>( callback: (params: any) => Promise<T>, { page = 1, pageSize, }: { page?: number; page ...

Discover the power of lodash's .groupBy method as you learn how to efficiently group objects within another

Utilizing lodash's _.groupBy function, I have generated the following data: { "Generic Drugs":[ { itemDes: "Dulcolax", itemGeneric: "Bisacodyl", pr ...

Using Vue.js to toggle rendering based on checkbox selection

Struggling to conditionally render form elements in Vue based on user input. I can do this with VanillaJS or jQuery, but struggling to implement it with Vue's built-in conditional directives. Using single-file components with the webpack template from ...

Can terminating a POST XHR request be trusted?

Running an apache server with PHP 5.4. I've set up a form that sends an asynchronous request to the server and stops any previous requests if the button is clicked again before the current request is completed. If I repeatedly click the button quick ...

Tips for combining two htmlelements together

I have two HTML table classes that I refer to as htmlelement and I would like to combine them. This is similar to the following code snippet: var first = document.getElementsByClassName("firstclass") as HTMLCollectionOf<HTMLElement>; var se ...

Customizing Material-ui picker: concealing text field and triggering modal with a button click

I'm currently working with version 3.2.6 of the material-ui pickers library to develop a component that has different renderings for mobile and desktop devices. For desktop, I have set up a standard inline datepicker with a text input field, while fo ...

What is the best way to enhance a state's capabilities in Machina.js?

When using Machina.js (version 0.3.6), how can I instantiate a modified FSM constructor where both the child and parent FSMs define behaviors in the same states? Here is the code snippet: var _ = require('lodash'); var machina = require('m ...

Choose the specific selector following the current selector

Consider this example of code: <script> $(document).ready(function () { $('span').each(function () { $(this).html('<div></div>') ; if ( $(this).attr('id') == 'W0' ...

Exploring the world of ASP .NET development with the powerful Sonar

We're currently working on an ASP .NET project and are looking for a way to analyze JavaScript files on-the-fly. Unfortunately, SonarLint only offers analysis for C# files. The incremental analysis feature seems to have been phased out, and issues ana ...

Is the parent node of the input element the input element itself?

When working with a DOM object obj of type <input>, I encountered an issue where attempting to obtain its parent node using obj.parentNode resulted in the same obj being returned. Is this behavior specific to <input> objects? What other types o ...

Interactive questioning system using Javascript/jQuery for Quick Responses

Hi there! I'm new to StackOverflow and a bit of a beginner when it comes to javascript/jquery. My current project involves creating a chat interface that looks like SMS text messages. Right now, I have users inputting text and using javascript to disp ...

Updating the value of a key in an object is not functioning as expected

There is a single object defined as requestObject: any = { "type": 'type1', "start": 0, "size": 10, "keywords": ['abcd','efgh'], filters: [], } Next, attempting to change the value for keyword, I updat ...

How can you use ng-click to re-sort data that has already been loaded using Angular's ng-click?

I'm having trouble switching between loading and sorting the information in the table using ng-click. The functions to load and sort work correctly individually, but I can't seem to switch between the two. It seems like I reset the countries data ...

Troubleshooting Angular 2: Instances of Classes Not Being Updated When Retrieving Parameters

I am facing an issue with the following code snippet: testFunction() { let params = <any>{}; if (this.searchTerm) { params.search = this.searchTerm; } // change the URL this.router.navigate(['job-search'], {q ...