CSS Cards Layout with Flexbox

Flexbox allows you to create a responsive CSS cards layout with minimal code. The example in this snippet will use a media object for each card, but technically the cards could be just about any kind of content.

The HTML will look like this:

<main class="container"> <div class="card"> <img src="image.png" class="img"> <div class="content"> <h3>Card Title</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> </div> <! – more cards here... – > </main>

I’ve used an image in the HTML code above, but note that in the demo I’m using a <div> as a mock image element in each card. The mock element is just for demonstration purposes. As mentioned, the content could be anything, including a real image.

The pertinent CSS looks like this:

.container { display: flex; flex-wrap: wrap; justify-content: space-around; } .card { width: 30%; display: flex; }

No floats or other old-school techniques needed, the cards will just work using these basic styles. The rest of the styles found in the demo below are for aesthetic purposes.

The CSS uses justify-content: space-around and a width of 30% on each card. You can adjust these if you want smaller or larger cards or if you want to use space-between instead.

The layout of the cards in a narrow viewport causes the cards to display on separate lines (which is fine for smaller devices), so you’ll have to View the CodePen demo in a separate window to see the full effect.

The demo for this CSS cards layout also includes a couple of buttons to allow you to interactively add and remove cards so you can see how the layout behaves using more or fewer cards.

Note: To the best of our knowledge, the information above and the snippet are accurate and up to date. However, in case you notice something wrong, please report snippet or leave a comment below.
Back to SnippetsShow Comments

Or start the conversation in our Facebook group for WordPress professionals. Find answers, share tips, and get help from other WordPress experts. Join now (it’s free)!