html - 是否有一种 pre-CSS3 方法可以使 div 向上翻译与其高度相同的量?

标签 html css

我想做的相当于

<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%) 属性,这是否可能?

最佳答案

不只使用 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 */}

关于html - 是否有一种 pre-CSS3 方法可以使 div 向上翻译与其高度相同的量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29956805/

相关文章:

javascript - addClass 函数工作正常,但removeClass 函数无法在表单的输入文本字段上工作?

html - 如何使用 HTML 和 CSS 创建营业时间列表?

jquery - Megamenu 在 vi​​sual composer wordpress 中的 Logo 之前加载

html - 行全宽中的 Bootstrap 跨度元素

css - 链接到 div 的 ID 从 div 顶部以下开始?

javascript - 我的 Canvas 游戏中有不同的 'states'

javascript - 是否有像 Google Analytics 那样生成折线图的 svg 库?

css - 浏览器可以像仅使用 Flex Box 或 CSS 制作的选项卡吗?

css - input[type=submit] CSS 在 Internet Explorer 6 中不工作

javascript - overflow-y :scroll and height:100vh 时如何滚动底部