Pew Pew Laser Blog

Code. Glass art. Games. Baking. Cats. From Seattle, Washington and various sundry satellite locations.

Pew Pew Laser Blog Archives — by Blog ID

CSS for Variable Height Elements in a Grid.

12.16.2013

Assume that you need to build a grid with multiple elements using CSS and HTML, where the height of each element varies due to different lengths of content. I think of this as "The CD Problem", displaying a list of CD covers with wildly different album titles. If you just float each element left, then the taller elements will break the grid and your whole layout: Broken grid of HTML elements

This is the solution to the breaking grid:

li:nth-child(4n+1) { clear:left; } That CSS says to clear: left; every 4th li (after the 1st one). clear: left; causes the element to force a new grid row to start.

Here is some example HTML:

<ul>
  <li>
    <h4>Bacon ipsum dolor</h4>
    <img src="http://placekitten.com/100/100?image=1" />
    <p>Sit amet short ribs pork chop sandwhich pork belly</p>
  </li>
  <li>
    <h4>Pastrami andouille</h4>
    <img src="http://placekitten.com/100/100?image=2" />
    <p>Boudin chuck ground round</p>
  </li>
  ...
</ul>

And the CSS:

li:nth-child(4n+1) {
    clear:left;
}

li {
  width: 20%;
  margin: 0 .5rem .5rem 0;
  padding: 1%;
  float: left;
  border: solid black 1px;
  text-align: center;
}

ul {
  list-style: none;
  padding: 0;
  font-size: small;
}

img {
  max-width: 100%;
}

h4 {
  margin: .5rem;
  text-transform: capitalize;
}

p {
  margin: .5rem;
  text-align: left;
}

You can fiddle with a live example on CodePen.

Permalink

Tags: code css web-development

Authorized users may log-in to leave a comment.

Last Blog: File Generators.

Next Blog: Quick Notes from Cascadia JS 2013.