Conformed Box Heights
(creating uniformed containers when the content isn’t)
In grid based web design, a common design pattern is several boxes aligned in a row. These boxes usually house some text, a link, maybe an image or something like that. and that content is usually never the same height. This becomes a problem if they have different background color or anything else distinguishing for a box. You can sometimes set a height in CSS, but what if the content is dynamic? You’ll be left with an ill fitting containing with content that is either overflowing or with uneven padding on the bottom. How do you fix this?
I usually use conforming box heights, a small jQuery script. CBE is simple to implement if you’re using jQuery or a derived library. Give the container a class of “conform”. The child elements will be given the parent‘s height.
// Conformed Heights - change .conform to your element
var conformedBoxes = $('.conform');
conformedBoxes.each(function(){
// Gets height of element
var height = $(this).height();
// Apply height to children
$(this).children('.box').css("height", height);
});
The above code requires that you do not put margins on the child elements. You must also declare box-sizing: border-box on the child elements, to absorb the padding into the total height. If you must use margins, then the code below should fit your needs:
// Conformed Heights — change .conform to your element
var conformedBoxes = $(‘.conform’);
conformedBoxes.each(function(){
// Gets height of element
var height = parseFloat($(this).height()),
// Get top and bottom margins
marginBot = parseFloat($(this).children(‘.box’).css(“margin-bottom”)),
marginTop = parseFloat($(this).children(‘.box’).css(“margin-top”)),
// subtract margins from height
height = height-(marginTop + marginBot);
// Apply height to children
$(this).children(‘.box’).css(“height”, height);
});
And if you are unable to declare box-sizing while having to use margins on the child elements, then this code should work:
// Conformed Heights — change .conform to your element
var conformedBoxes = $(‘.conform’);
conformedBoxes.each(function(){
// Gets height of element
var height = parseFloat($(this).height()),
// Get top and bottom margins
marginBot = parseFloat($(this).children(‘.box’).css(“margin-bottom”)),
marginTop = parseFloat($(this).children(‘.box’).css(“margin-top”)),
paddingBot = parseFloat($(this).children(‘.box’).css(“padding-bottom”)),
paddingTop = parseFloat($(this).children(‘.box’).css(“padding-top”)),
// subtract margins from height
height = height-((marginTop + marginBot)+(paddingTop + paddingBot));
// Apply height to children
$(this).children(‘.box’).css(“height”, height);
});
For any questions or comments, feel free to tweet to me. This is the first entry of one-night-only, a series where I try to solve a stupid problem in just 30 minutes of coding. View the series on github.
Email me when Chad Humphrey publishes or recommends stories