Why does margin move elements?

Hi guys,

For anybody that is familiar with HTML and CSS, I've read and watched quite a few tutorials on padding and margin but none of them explain why adding margin to an element moves the element but doesn't resize it.

Let's take a heading tag H1, this is a block line element, if we set the background-color we can see that the element will take up the full length of its container.

Now if we add a margin-right of 20px to that H1 element it gives it a margin-right of 20px! But what confuses me is we're adding a margin yet the element or box it contains doesn't get larger? by this I mean it still takes up 100% of its containing element.

Yet somehow all it seems to do is move the content of the element 20px to the right! I thought if we added a margin the box( which contains margin,padding,border,content) would also get bigger and in my case it would add 20px to the already 100% width.
I’m not entirely sure what you are asking.

In the “box model” the content area does not change size, but the total size of the element does, in fact, change, because the margin is part of the total size of the element.

As the layout engine arranges elements onto your page they do so using the total size of your element. What affects its position are the CSS rules that modify one or more of the margin, border, padding, and content areas. The layout engine is permitted to add unused space around your element as needed.

Since the total size of your element is fixed at 100%, changing the right margin can’t change the total size of the element — it just makes the right margin fatter, so the space available to the border, padding, and content is smaller and somewhat leftward of what it was before.

Visually, you can look at it like this:

  ┌────────┐
  │ ┌────┐ │
  │ └────┘ │
  └────────┘
  ┌────────┐
  │ ┌───┐  │
  │ └───┘  │
  └────────┘

The total width of the element (margin + border + padding + content) is still 100%, but the right side margin is now twice as wide, leaving less room for the (border + padding + content) of the element.

Hope this helps.

[edited for clarity]
Last edited on
Topic archived. No new replies allowed.