简体   繁体   English

如何在页面的绝对中心 position 一个 div?

[英]How to position a div in the absolute center of a page?

Here's how I'm doing it and it does work:这是我的做法,它确实有效:

#myDiv { background: red; width: 100px; height: 100px; margin-top: -50px; margin-left: -50px; position: absolute; top: 50%; left: 50%; }

<div id="myDiv"></div>

But the problem is when I scroll down the page, the div no longer appears in the center because it is positioned 50% off the top relative to the original view port height, not the current one.但问题是当我向下滚动页面时,div 不再出现在中心,因为它相对于原始视口高度而不是当前视口高度位于顶部的 50% 处。 So I guess I would have to listen for a document scroll event and update the position of the div dynamically.所以我想我必须监听文档滚动事件并动态更新 div 的 position。 Any idea how to do that?知道怎么做吗?

Basically the effect I'm after is for the div to always be in the center even when the user scrolls.基本上我所追求的效果是,即使用户滚动,div 也始终位于中心。

or maybe there's even a pure css solution?或者甚至可能有一个纯粹的 css 解决方案?

Use position: fixed;使用position: fixed; instead of position: absolute;而不是position: absolute; The positioning (top, left etc) will remain the same, but in relation to the window, and not the document.位置(顶部、左侧等)将保持不变,但与 window 相关,而不是文档。

http://jsfiddle.net/jasongennaro/25WAg/ http://jsfiddle.net/jasongennaro/25WAg/

You're going to want position: fixed;你会想要position: fixed; . .

To achieve the div in the center of the screen, you're going to want left: 50%; margin-left: -50px;要在屏幕中心实现 div,您需要left: 50%; margin-left: -50px; left: 50%; margin-left: -50px;

Note that the negative margin-left is half of the container's width请注意,负边距左是容器宽度的一半

#myDiv {
    background: red;
    width: 100px;
    height: 100px;
    margin: auto;
    position: fixed;
}

#container {
    width: 90%;
    height: 90%;
}

Then for your HTML:然后对于您的 HTML:

<div id="container">
    <div id="myDiv">DATA</div>
</div>

Tell me if it works.告诉我它是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM