我想将.presentation
div垂直居中但带动画。从下到上的位移为10%。
我需要保留将不同的高度值设置为父级div .parent
的可能性,例如75%或100%,但我的文本保持垂直居中。
我可以帮忙吗?
http://jsfiddle.net/Xroad/4t9vsym3/2/
$('.presentation').animate({
top: '40%',
opacity: '1'
}, 1700, function () {});
.parent {
height: 75%;
width: 100%;
background: red;
}
.presentation {
position: absolute;
max-width: 1100px;
margin: auto;
top: 50%;
left: 0;
bottom: 0;
right: 0;
opacity: 0;
text-align: center;
z-index: 1;
}
答案 0 :(得分:1)
您可以使用css变换将文本的位置偏移高度的一半:
-webkit-transform: translateY(-50%);
-ms-transform: translateY(-50%);
transform: translateY(-50%);
例如:http://jsfiddle.net/4t9vsym3/6/
P.S .parent
应为position:relative
,以便.presentation
正确定位在其中。
答案 1 :(得分:0)
您的代码中的缺陷是您尝试将文本顶部的偏差近似10%(50% - 10%= 40%)。而应该通过$('.presentation').outerHeight() / 2
计算此偏差
看看这个fiddle。
我将文本直接放在应该居中的div下面,然后通过($('.parent').outerHeight() - $('.presentation').outerHeight()) / 2
让它动画显示
等于
$('.parent').outerHeight()/2 - $('.presentation').outerHeight() / 2
(我还将overflow:hidden
css-property设置为.parent)
修改强>
我使用h2-top和height作为参考重新调整计算..现在无论内容如何都集中在
var $par = $('.parent');
var $pres = $('.presentation');
var initTop = $par.offset().top + $par.height() * 0.9;
$pres.offset({left: $pres.offset().left , top : initTop});
var delta = $pres.find('h2').offset().top - ($par.offset().top + ($par.height() - $pres.find('h2').height()) / 2);
$pres.animate({
top: '-=' + delta,
opacity: '1'
}, 1700, function () {});
答案 2 :(得分:0)
您只需要做一些快速高度计算。
元素的顶部位置应为:
( heightOfParent - heightOfCenteredElement ) / 2
这是一个小提琴:http://jsfiddle.net/urmg48ba/
编辑:小提琴被打破了。更新。