是否有一种预先的CSS3方式使div向上翻译的高度与其高度相同?

时间:2015-04-30 00:10:44

标签: html css css3

我想做的是等同于

<style>
 .bump-up { 
     height: 100px;
     margin-top: -100px; 
  }
</style>

<div class="bump-up">
    <p>This should translate the div upwards the same amount as it's height. For example, if the div is 100 pixels in height, then it will be translated 100 pixels higher than it otherwise would've been.
    </p>
</div>

除了一般情况,它在实现中不需要任何精确的像素。这可能不使用CSS3的transform:translateY(-100%)属性吗?

1 个答案:

答案 0 :(得分:1)

不使用css,但这可以使用javascript。

Demo

HTML

<div id="moveMe">Hello World!</div>

CSS

html,body {
    margin: 0;
    padding: 0;
    height: 100%;
}
#moveMe {
    position: relative;
}

JAVASCRIPT

var moveMe = document.getElementById("moveMe");
var docHeight = document.body.scrollHeight;
var divHeight = moveMe.offsetHeight;
moveMe.style.top = ((docHeight / 2) - (divHeight / 2)) + "px";

确保将您的脚本放在DOM之后(或在body标记的末尾)或用window.onload = function() { /* script here */ }

包装脚本