Best practices for alignment/margins

In building out websites, I like to do a lot of alignment. For example, I like the left edge of my nav-menu to align with the left edge of my header text, and the left edge of the image in the next section–etc, etc.

There are two main ways of doing this, as I see it.

  1. apply padding to the body or some container that spans the whole document
  2. apply padding or margin to nested divs or elements

I’ve been doing (2), applying padding to the maybe 6 sections I have. The problem with that is that I have to rejigger this for my responsive breakpoints (using one for tablet and one for mobile).

Is there a generally accepted way of dealing with this issue?

I’ve dealt with this issue for a while, before I figured out a way that works for me. I usually have one class .wrapper with only

  • a max-width
  • margin: 0 auto or 32px auto or whatever vertical spacing you need
  • horizontal padding

This class gets applied to all sections. For different viewports, I adjust the max-width and the padding once in a media query. The vertical paddings, if needed, are taken care of by the inner elements. Those rarely change with viewport width.

Your way number 1 is problematic, because I often have an element (like a header) with a background colour that should span the whole viewport. In this case, I’d use my wrapper class on an inner element like this:

<header>
    <div class="wrapper">
        <!-- content -->
    </div>
</header>

I like it. You always got the goods, @jdisco!

Nah I’m just a couple of months ahead of you in CSS, at max. This exact question gave me headaches for a long time, I could only solve it after a lot of practice. Your thinking just gets boxier. It’s all overlapping rectangles.

1 Like