neiker
neiker

Reputation: 8991

Strange behavior on computed height and childrens margin

I want to know the real height of an element no matters what it have inside. That's easy. The problem began when I put away the borders of the element and notice an strange behavior, see it here: http://jsfiddle.net/LypZR/

First div: 122px: OK (children height 100px, children margins 20px, border 2px)

.bordered {
    border: 1px solid #000;
}

Second div: 120px: OK (children height 100px, children margins 20px)

.display-inline-block {
    display: inline-block;
}

Thirth div: 100px: What? where are the margins?

I solved it using display: inline-block that works just fine for me (in this particular case). But I really want to know what is exactly happening.

Upvotes: 0

Views: 126

Answers (3)

lizardhr
lizardhr

Reputation: 310

you can see real height without any collapse if you use the right css selector for all the elements *, so:

* {
    height: 100px;
    margin: 10px;
}

Like you did it's like a quirk behave for me because I don't know .element selector, and if you look inside the consolle could you see that no margin is applied in the styles tab, but only a computed height is calculated, perhaps for some strange behavior it isn't suppouse to work right. till I know only height width and padding are considerate for real element dimensions. margins should not be considerate for real element dimensions, this is only an IE issue who do such calc adding margin to real element dimensions. jsfiddle

Upvotes: 0

theHarsh
theHarsh

Reputation: 680

That's called the margin collapsing. When the child element is given margin and parent element don't have any content in it, this happens.

add this class and its done.

.no-bordered{
    overflow:auto;
}

Fiddle : http://jsfiddle.net/LypZR/3/

Upvotes: 0

Palpatim
Palpatim

Reputation: 9262

I think you're getting surprised by margin collapsing.

The two cases that margins collapse are between adjacent sibling elements and between parent and child elements.

In your case, it's the parent/child collapse that's causing you grief: If you have nothing interesting between the top margin of your parent and the (top margin of its first child|bottom margin of its last child), the parent margin collapses. The transparent border hack is commonly-used in these cases.

You probably noted that it didn't change the actual layout values--the p tag's margin kept the visible elements from collapsing into each other. But I admit it's counterintuitive.

Upvotes: 1

Related Questions