Vertical aligning child with absolute position and auto-field failover in FireFox

I am trying to align a child within a parent container. Below is a snippet of code. Just the basics to get it working:

// HTML //

<div class="parent">
    <div>Parent</div>
    <div class="child"></div>
</div>


// CSS //

.parent { position: relative; }

.child {
    position: absolute;
    margin: auto;
    height: 60px;
    width: 40px;
    top: 0;
    right: 0;
    bottom: 0;
}

      

Chrome and IE Chrome and IE

Firefox Firefox

View an example on jsfiddle

If you view this in Chrome or IE, it is mid-aligned. But this is not the case in Firefox. Is this a Firefox bug, or are Chrome and IE doing it wrong?

When you make the child smaller than the parent (in height), it is also correctly centered in Firefox. Only when it is bigger will this problem appear.

+3


source to share


2 answers


Remove the bottom attribute from the child and set the top to "-20px". This has been tested to work in Firefox DE ^^. You can also -100%, I would say it will cause problems if the height of the parent changes, however with the given height on the child, if the height of the parent has changed, you probably have to use calc.



0


source


I think I found a way to fix this, so it behaves the same in Chrome, IE and Firefox.

Instead:

top: 0;
bottom: 0;

      

I tried:



top: 50%;
transform: translateY(-50%);

      

This seems to work even in IE9.

View example on jsfiddle

0


source







All Articles