jQuery: automatic CSS gutters when the box-sizing property is not supported

A common task in CSS development is to add a certain amount of space between text and the boundaries of its container. This task is made difficult when an element has a stated width and you cannot add padding without breaking the box model. CSS3 allows you to use the box-sizing property, but this feature is not supported by older browsers. To fix this problem, you have to create gutters.

Usually we have to manually insert gutters directly in the HTML structure of an element:


<div class="box">
	<div class="gutter"><!-- text --></div>
</div>

We can automate this process (and keep our markup clean) by using jQuery:


(function ($) {
    $.fn.gutter = function (options) {
        var settings = {
            tag: 'div',
            className: 'gutter'
        };

        options = $.extend(settings, options);

        return this.each(function () {
            var $element = $(this),
                element = $element[0];
            if (element.firstChild.nodeType == 3) {
                var wrapper = '<' + options.tag + ' class="' + options.className + '"></' + options.tag + '>';
                $element.wrapInner(wrapper);
            }

        });

    };


})(jQuery);

Example:


$(function () {
    $('div.box').gutter();

});

[view-example url="http://jsfiddle.net/gabrieleromanato/UjbsW/"]
Back to top