DEV Community 👩‍💻👨‍💻

DEV Community 👩‍💻👨‍💻 is a community of 968,547 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for Four ways to align boxes horizontally, each in under three lines of CSS
Robert Mion
Robert Mion

Posted on

Four ways to align boxes horizontally, each in under three lines of CSS

Start with semantic HTML

<ul>
  <li>
    <img src="https://placehold.it/300x180" alt="" />
    <h2>Text label</h2>
    <p>Descriptive text</p>
  </li>
  <li>
    <img src="https://placehold.it/300x180" alt="" />
    <h2>Text label</h2>
    <p>Descriptive text</p>
  </li>
  <li>
    <img src="https://placehold.it/300x180" alt="" />
    <h2>Text label</h2>
    <p>Descriptive text</p>
  </li>
</ul>
Enter fullscreen mode Exit fullscreen mode

List with three items

Add some declarations to reset a few browser default styles

/* Resets */
img {
  max-width: 100%;
}
ul {
  padding: 0;
  list-style-type: none;
}
Enter fullscreen mode Exit fullscreen mode

Four options to stack the list items horizontally instead of vertically

1. CSS Columns: 1 declaration

ul {
  columns: 3;
}
Enter fullscreen mode Exit fullscreen mode

Layout using CSS columns

2. Inline-block display with calc(): 2 declarations

li {
  width: calc((100vw / 3) - 20px);
  display: inline-block;
}
Enter fullscreen mode Exit fullscreen mode

Layout using inline-block and calc

3. CSS Flexbox: 1 declaration

ul {
  display: flex;
}
Enter fullscreen mode Exit fullscreen mode

Layout using CSS flexbox

4. CSS Grid: 2 declarations

ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
Enter fullscreen mode Exit fullscreen mode

Layout using CSS grid

Keep it simple. Don't feel stupid.

Want to practice? Here's two free resources.

  1. FrontEndMentor.io
  2. FreeCodeGame.com

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.