1 reply [Last post]
rafael.soteldo
rafael.soteldo's picture
Offline
newbie
Last seen: 3 years 35 weeks ago
Timezone: GMT-4.5
Joined: 2015-10-24
Posts: 8
Points: 27

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

Rafael

AttachmentSize
Fig 1.png4.4 KB
Fig 2.png4.1 KB
gary.turner
gary.turner's picture
Offline
Moderator
Dallas
Last seen: 2 days 14 hours ago
Dallas
Timezone: GMT-6
Joined: 2004-06-25
Posts: 9743
Points: 3822

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.

Example:

    .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">
	...
      </div>
    </div>

cheers,

gary

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