1 reply [Last post]
rafael.soteldo's picture
Last seen: 6 weeks 5 days ago
Timezone: GMT+12
Joined: 2015-10-24
Posts: 10
Points: 30

Hi there:

I'm new to CSS.

In order to explain myself, I came up with this little piece of code, in the HTML, it is just two nested divs, the outer div has a class of outer and the inner has a class of inner

.outer {
	width: 200px;
	height: 200px;
	background: url(_images/grid.gif); /*This is just a grid*/
	background-position: 5px 5px;
.inner {
	width: 150px;
	height: 50px;
	border: 5px solid brown;
	padding: 5px;
	margin: 10px;

It produces what's depicted in Figure 1, note that the top margin of the .inner box is collapsed to 0.

But if I add a border to .outer then the top margin of the .inner is respected (See Fig 2)

It only happens when it's the first element on the normal flow page

What's the CSS rule that determines the collapse of the first element when no border or padding has been set to its container?

Thanks in advance


Fig 1.png4.4 KB
Fig 2.png4.1 KB
gary.turner's picture
Last seen: 2 years 3 weeks ago
Timezone: GMT-6
Joined: 2004-06-25
Posts: 9776
Points: 3858

It always happens; first, last or in between.

See Meyer on margin collapse.

Meyer left off or didn't know about block formatting context. Setting overflow to other than 'visible' will trigger a new block formatting context. So will various display values, e.g. inline-block or table. Likewise set float right|left.


    .outer {
        display: inline-block;
        background-color: yellow;
        width: 200px;}
    .inner {
	height: 50px;
	border: 5px solid brown;
	padding: 5px;
	margin: 10px;}

    <div class="outer">
      <div class="inner">



If your web page is as clever as you can make it, it's probably too clever for you to debug or maintain.