Search code examples
reactjstailwind-css

Center a card using grid and tailwind


I am using React and tailwind to display the data of 5 items like below

<div className="grid grid-cols-1 md:grid-cols-3 xl:grid-cols-5">
   {data.map((item) => (
      <Card key={widget.id} widget={widget} />
   ))}
</div>

My question is on the medium screens I want to have the 2 items (4 and 5) to be centered because now they are aligned to the left.

I have tried to use tailwind documentation but I didn't get anything. if any one can help me with that I would be appreciated.

Thanks


Solution

  • You could have double the grid column tracks, with the grid items spanning two columns. This then lets you offset the fourth and fifth items by one column track, thus centering them:

    const widget = {};
    const data = Array(5).fill();
    
    const Card = () => <div className="border h-10 md:max-xl:col-span-2 md:max-xl:[&:nth-last-child(2)]:col-start-2" />;
    
    const App = () => (
      <div className="grid grid-cols-1 md:grid-cols-6 xl:grid-cols-5">
         {data.map((item) => (
            <Card key={widget.id} widget={widget} />
         ))}
      </div>
    )
    
    ReactDOM.createRoot(document.getElementById('app')).render(<App/>);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.tailwindcss.com/3.4.1"></script>
    
    <div id="app"></div>