Domanda

I've got an absolutely positioned child inside a relatively positioned parent. The child is supposed to appear vertically centered next to the parent. See this jsFiddle: http://jsfiddle.net/wAY3T/

The problem is that both the parent's and the child's heights are unknown at design-time, so I tried using percentages with the negative margin method, but the outcome goes completely insane and I can't figure out what's wrong with my code.

HTML:

<div class=parent>
    <div class=child>Absolute div</div>
    Some content of the parent
</div>

CSS:

.parent {
    position: relative;
}

.child {
    position: absolute;
    right: 100%;
    top: 50%;
    margin-top: -50%;
}

The child then displays somewhere far on top of the parent, even though the code looks like it would vertically center it. In the fiddle, the -50% margin calculates to -112px. WTF?

If you have any idea what's going on, please help me. I've been struggling for hours.

È stato utile?

Soluzione

Percentage margin is always relative to the containing block's width, so this won't work like you expect.

If you're open to an alternative, I suggest instead using:

.parent {
    position: relative;
}

.child {
   -o-transform: translateY(-50%);
   -webkit-transform: translateY(-50%);
   -moz-transform: translateY(-50%);
   -ms-transform: translateY(-50%);
    transform: translateY(-50%);
    position: absolute;
    right: 100%;
    top: 50%;
}

Updated fiddle (this is supported quite well except for IE8)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top