Keeping Your Element Height in Multiples

Say for example, your designer suddenly decides that having a postage stamp border on a site is a good idea, and tells you to code it up. You quickly realise that your side borders are going to have weird looking cutoffs.

There are two options: a) in CSS make your line-heights, paddings, and margins of all elements always add up to the correct number to display the border properly, or b) add a few lines of jQuery to adjust the height for you.

$(function(){

  var multiple = 20;
  $('.post').each(function(){
    if($(this).innerHeight() % multiple != 0){
      $(this).height(
        parseInt($(this).height()) +
        (multiple - $(this).innerHeight() % multiple)
      );
    }
  });

});

This code gets the current height of the element as well as the top and bottom padding. It checks if this isn't a multiple of 20 (how high the repeating element is for the stamp). If not, it adds whatever is needed to reach the next highest multiple and sets it as the element height.

So there you are — keeping your designs in shape with jQuery. View a demo here.

Comments

2 responses to “Keeping Your Element Height in Multiples”

  1. How could I set this up so that it works separately on each member of a class? At the moment it applies the correct height to the first div which has the class, but then applies the same height to all the other divs too. I want to have text inside my divs, so I’d like the algorithm above to work separately on each div that has that class in this example:

    http://blog.sound-guru.com/

    I don’t have much experience with Javascript or JQuery, just trying to solve a specific design problem. Does it have anything to do with the each() command? Would be really grateful if you could help.

  2. Hi Tom,

    I’ve updated the code in the post to be a lot shorter and you can use it for a class or id properly. View a demo here https://justjquery.com/lab/heighttest/

Leave a Reply

You must be logged in to post a comment.