Pankaj
Parashar

Developer. Designer. Writer.

Hello. I'm Pankaj Parashar, 30yo frontend designer, developer from Mumbai, India. I make things for the web and write about them on my blog here.

Elsewhere,
Twitter | Github | Codepen

Negative Margin, Positive Padding

Neat little trick I learned from Joshua Hibbert's website, where he has effectively used this technique to design backgrounds stretching infinitely on either directions but the content respects the width.

Published on Jul 06, 2014

Ever wondered, how you can stretch the background of the container beyond the viewport but the content should not exceed the defined width? Well, if you are looking closely, then the answer is all over the place on this website. As I have used this technique, to design the blockquotes, pre, and code blocks on my website.

Technique

The idea stems from the box model technique, in which you can apply negative margins on block child container for them to stretch outside the parent container. We use this idea of negative margins to stretch the background of the container to the entire width of the webpage. For example, margin-left: -999em will stretch the left margin of the box to far left, which in this case is outside the viewport (-999em is the magic number).

Problem

This however, causes one problem, which also pulls the content (or the text) outside of the parent container, which destroys the alignment and flow of the content. This can be solved by using the exact same number to push the content right where it belongs with padding-left: 999em. This ensures that the background covers the entire left portion of the web page, but the content still respects the width.

Variations

Interestingly, this technique not only works for fixed-width containers but also fluid width containers and also not only works horizontally (for widths) but also vertically (for heights).

Mixins

Without a doubt, the next thing I hopped into are handy Sass-mixins to leverage this technique for your projects.

@mixin align($num: 999em, $dir: 'left') {
    @if $dir == 'center' {
        margin: 0 -#{$num};
        padding: 0 #{$num};
    }
    @else if $dir == 'middle' {
        margin: -#{$num} 0;
        padding: #{$num} 0;
    }
    @else {
        margin-#{$dir}: -#{$num};
        padding-#{$dir}: #{$num};
    }
}

.. and the usage of this mixin, for each type of variation,

.left-align {
    @include align($dir: 'left');
}

Previous
Random Colors in Sass

Next
Designers Guide to DPI