0

This question seems not so significant as others but I'd like to understand how it works and why it works this way.

We have a very simple code pen here:

html, body {
  margin: 0;
  padding: 0;
}
.header {
  background-color: #ccc;
  /* border: 3px solid pink; */
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>test1</title>
</head>
<body>
  <div class="header">
    <h1>Header</h1>
    <h2>Subheader</h2>
  </div>
</body>
</html>

When border is commented the pen works like this:

margins not colored

We can see that h1 and h2 margins are not colored by property 'background-color'. Here I thought that 'ok, it's because it's only what div.header contains.

But if we are removing comments and make a border for div.header it suddenly becomes behave different. margins have been colored by border

Now h1 and h2 margins became a part of div.header though border is only thing that changed. Can you help me explain this phenomenon. I know this has a logical explanation. Thank you very much.

1 Answers1

8

The border doesn't have any (direct) effect on the background colour, it has an effect on the margins.

Without a border, the top and bottom margins of the child elements collapse through the edge of the element.

When you add a border, those margins stop at the border pushing the child elements away from it and increasing the size of the element inside the border (which is filled with the background colour).

See this article for further reading.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335