concept margin in category css

appears as: margin, margins, margin, margins
CSS in Depth

This is an excerpt from Manning's book CSS in Depth.

Shorthand property order particularly trips up developers when it comes to properties like margin and padding, or some of the border properties that specify values for each of the four sides of an element. For these properties, the values are in clockwise order, beginning at the top.

Take another look at your page. Notice something strange going on with the margins? You haven’t applied any margin to the header or the container, yet there’s a gap between them (figure 3.16). Why is that gap there?

Figure 3.16. Gap caused by the margins collapsing

This is a little strange. In this case, you want the <h1>’s margin to stay inside the <header>. Margins don’t always collapse exactly to the spot where you want. Fortunately, there are a number of ways to prevent this. In fact, you’ve already fixed it for the main section of the page; notice that the margin above “Come join us!” doesn’t collapse upward outside of its container. That’s because the margins of flexbox items don’t collapse, and you laid out that part of the page using a flexbox.

Padding provides another solution. If you add top and bottom padding to the header, the margins inside it won’t collapse to the outside. While you’re at it, let’s update the header so it looks like figure 3.18, and apply left and right padding as well. To do so, update your stylesheet to match listing 3.14. You’ll notice this now means there’s no margin between the header and the main content. We’ll come back to address that shortly.

Figure 3.18. Adding padding to the header prevents margin collapsing
Listing 3.14. Applying padding to the header

Here are ways to prevent margins from collapsing:

  • Applying overflow: auto (or any value other than visible) to the container prevents margins inside the container from collapsing with those outside the container. This is often the least intrusive solution.
  • Web designer Heydon Pickering once said margins are “like applying glue to one side of an object before you’ve determined whether you actually want to stick it to something or what that something might be.” Instead of fixing margins for the current page contents, let’s fix it in a way that works no matter how the page gets restructured. You’ll do this with something Pickering calls a lobotomized owl selector. It looks like this: * + *.

    sitemap

    Unable to load book!

    The book could not be loaded.

    (try again in a couple of minutes)

    manning.com homepage
    test yourself with a liveTest