Timwi
Timwi

Reputation: 66604

Why is 'top' property ignored when relatively positioning an element with no explicit height?

I am not looking for a different solution to the question of centering elements; I am looking for an explanation why the solution presented here doesn’t work.

Consider the following jsFiddle:

Here’s the HTML/CSS code for reference:

HTML

<div class='outer'>
    <div class='middle'>
        <div class='inner'>
            Text should be centered
        </div>
    </div>
</div>

CSS

.outer {
    position: absolute;
    left: 200px;
    top: 50px;
    width: 100px;
    height: 100px;
    border: 2px solid #00f;
    border-radius: 10px;
}

.middle {
    position: absolute;
    left: 50%;
    top: 50%;
    line-height: 1em;
}

.inner {
    position: relative;
    left: -50%;
    top: -50%;
    width: 5em;
}

The element inspector in both Chrome and Firefox tell me that both middle and inner have the correct width and height, and indeed the horizontal positioning is working correctly, but for some reason the top: -50% rule is ignored. However, it is only ignored if .middle doesn’t have an explicit height — if you add one, it works, even if the effective height is the same as what it is already. Why is this?

Upvotes: 3

Views: 1612

Answers (2)

Fractal Mind
Fractal Mind

Reputation: 462

For those coming after me try to add display:grid; on the parent of container

<div style="display: grid;">
    <div _ngcontent-serverapp-c11="">
        <video _ngcontent-serverapp-c11="" onloadedmetadata="this.muted=true" autoplay="" loop="" muted="" playsinline="" class="lazy vid-mobi"><source _ngcontent-serverapp-c11="" src="https://cdn3.blablabla.com/gtb/videos/intro_lg.mp4" type="video/mp4"> 
        </video>
    </div>
</div>

It works for me

Upvotes: -1

poke
poke

Reputation: 388383

This is the behavior as as specified in the old CSS 2 specification (emphasis mine):

<percentage>

The offset is a percentage of the containing block's width (for 'left' or 'right') or height (for 'top' and 'bottom'). For 'top' and 'bottom', if the height of the containing block is not specified explicitly (i.e., it depends on content height), the percentage value is interpreted like 'auto'.

In the current CSS 2.1 specification that restriction was removed, so I’d say it’s a cross-browser bug now. Firefox has a very old bug on this here that was marked as invalid because of the original spec; and there is a newer bug here could use some votes to get more attention.

Upvotes: 2

Related Questions