Transform not working when parent's height is set in viewport units

150 Views Asked by At

I'm having problems with vertical centering. The header has a height of 100vh, and its child element, site-info, has an unspecified height. The site-info element is supposed to be vertically centered within header.

I've tried the standard transform:translateY solution, but it doesn't work. Top:50% does work, but it's like the transform doesn't happen. I can see with FireBug that the transform property is attached to site-info, but nothing happens.

I've also tried using vertical-align: center on site-info with no success, and using some position:absolute solution for the header makes it disappear completely. Using position:absolute on site-info does not help either.

HTML:

<header>

    <div class="site-info">
        <h1>Title</h1>
        <p>some content</p>
    </div>

</header>

CSS:

header{
background-position:top center;
background-size:100%;
background-size:cover;
height:100vh;
position:relative;
text-align:center;
color:white;
overflow:hidden;
}

div.site-info{
position:relative;
text-align:center;
display:inline-block;
top: 50%;
-moz-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
}
2

There are 2 best solutions below

0
On BEST ANSWER

As I stated in a comment to my question, the issue was a conflict with animate.css; the FadeInUp animation.

I tried to vertically align the parent div with transform. I also wanted it to animate so I applied FadeInUp to it, without knowing that FadeInUp also used transform, causing conflict.

I solved the conflicting transform by applying the FadeInUp animation to the children (h1 and p) instead.

0
On

Since you know your parent container's height, you can use line-height and vertical-align in tandem as your child's display is inline-block:

header {
    background-color:grey;
    background-position:top center;
    background-size:100%;
    background-size:cover;
    height:100vh;
    line-height: 100vh; /* -- same as height -- */
    position:relative;
    text-align:center;
    color:white;
    overflow:hidden;
}
div.site-info {
    position:relative;
    text-align:center;
    display:inline-block;
    line-height: 1; /* -- reset to 1 as it will naturally inherit parent's enormous value -- */
    vertical-align: middle; /* -- This will work now -- */

   /* top: 50%;
    -moz-transform: translateY(-50%);
    -webkit-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);*/
}