Reputation: 503
Because of transform: translateZ(0);
position of h1 changes. If I remove it, effect not working properly.
How can I change below code and have h1 centered, and grow effect happens at the center of text?
I found a grow effect from here but the codes has transforms that conflict with each other
h1{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.hvr-grow {
transform-origin:center center;
display: inline-block;
vertical-align: middle;
/*transform: translateZ(0);*/
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
backface-visibility: hidden;
-moz-osx-font-smoothing: grayscale;
transition-duration: 0.3s;
transition-property: transform;
}
.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
transform: scale(1.8);
}
<div style="position:relative">
<h1 class="hvr-grow">Hello I'm centered</h1>
</div>
Upvotes: 0
Views: 197
Reputation: 1599
The problem lies in the positioning of your header. As you position it absolutely, the transform is starting always 50% from the edge. In order to have text animated properly, you can make the <h1/>
container 100% wide and then center the text inside using text centering CSS:
h1{
position: relative;
width: 100%;
text-align: center;
}
.hvr-grow {
transform-origin:center center;
display: inline-block;
vertical-align: middle;
/*transform: translateZ(0);*/
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
backface-visibility: hidden;
-moz-osx-font-smoothing: grayscale;
transition-duration: 0.3s;
transition-property: transform;
}
.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
transform: scale(1.8);
}
<div style="position:relative">
<h1 class="hvr-grow">Hello I'm centered</h1>
</div>
Upvotes: 1
Reputation: 66123
That is because you have applied two different CSS transforms to the same element: first, you have applied translate(-50%, -50%)
, and then you apply scale(1.8)
. The annoying thing about CSS transforms is that they do not stack, so basically your scaling will overwrite the translate... in other words, with your original code, the following styles will apply in the hover state:
transform: translate(-50%, -50%); /* This will be overwritten! */
transform: scale(1.8); /* Overwrites all preceding transforms */
What you can do is simply to combine them in the :hover
selector, i.e.
transform: translate(-50%, -50%) scale(1.8);
p/s: On a side note, since you are using the CSS transform trick to vertically center your element, you do not need to use display: inline-block
and vertical-align: middle
tricks.
Here is a working example:
h1{
position: absolute;
top: 50%;
left: 50%;
}
.hvr-grow {
box-shadow: 0 0 1px rgba(0, 0, 0, 0);
backface-visibility: hidden;
-moz-osx-font-smoothing: grayscale;
transition-duration: 0.3s;
transition-property: transform;
transform: translate(-50%, -50%);
}
.hvr-grow:hover,
.hvr-grow:focus,
.hvr-grow:active {
transform: translate(-50%, -50%) scale(1.8);
}
<div style="position:relative">
<h1 class="hvr-grow">Hello I'm centered</h1>
</div>
Upvotes: 2