DEV Community

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>

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;
}

Four options to stack the list items horizontally instead of vertically

1. CSS Columns: 1 declaration

ul {
  columns: 3;
}

Layout using CSS columns

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

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

Layout using inline-block and calc

3. CSS Flexbox: 1 declaration

ul {
  display: flex;
}

Layout using CSS flexbox

4. CSS Grid: 2 declarations

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

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

Discussion (0)