A fresh mix of code snippets and tutorials

jQuery align elements with the grid

When working on a CSS grid, here’s one way of aligning variable-height elements, such as blocks of pre-formatted code, advertisements, and so on.

For example, here at WP-Mix, the layout of each page aligns to a strict horizontal & vertical grid (also referred to as a CSS matrix). You can see it in action by clicking the “show matrix” button in the upper-right corner of any page on the site.

The technique I’m sharing here is used to ensure that all pre-formatted code examples (i.e., <pre> tags) align with the grid. Without this code, the variable-height <pre> elements would break the grid in some cases.

To prevent this from happening, the following slice of jQuery can be used to auto-align the target element(s) to the grid upon page load, and optionally upon window resize as well.

function adjust_element_grid(){
		var element   = $(this);
		var baseline  = 18; // grid
		var height    = element.height();
		var remainder = parseFloat(height % baseline);
		var offset    = parseFloat(baseline - remainder) + 15;
		element.css('margin-bottom', offset + 'px');
	}, 1500); // delay
	}, 1500); // delay

So, without going into too much detail, let’s look at some highlights of this technique:

  • As-is, this code aligns the target .element to an 18px vertical grid. To align to some other grid units, edit the baseline variable and then set the offset variable as needed to dial it in.
  • The element is aligned to the grid via bottom margin.
  • As-is, the adjust_element_grid() function is executed both on page load and on window resize, so that the grid remains perpetually intact.
  • In order to account for varying loading times, a slight delay (1500 ms) is applied before the resize function is executed. This may be adjusted or removed entirely depending on the situation.

That’s it in a nutshell. Again, check out the grid-based pages on this site to see this technique in action. Note that the sidebar ad for my book The Tao of WordPress is also aligned to the grid using this technique. At some point, I’ll replace the odd-height ad/image with one that is sized to fit with the grid (i.e., in some increment of 18px), thereby making it unnecessary to use the resize technique for that particular element.

★ Pro Tip: