2010-12-16 74 views
32

我想放置绝对位置在屏幕视图中心(滚动或不滚动)的div。在屏幕视图中心位置绝对div

我有这个,但它的位置div在文档中间而不是当前视图中间。

#main { 
    width: 140px; 
    height:100px; 
    border: 1px solid Black; 
    text-align: left; 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    margin-left:-70px; 
    margin-top:-50px; 
} 

回答

39

变化position:absoluteposition: fixed,你应该是好去!

当你说位置 - 绝对时,参考div是具有位置相对的父div。但是,如果你说固定位置,那么引用就是浏览器的窗口。这是你想要在你的情况下的扫管笏。

在IE6的我猜你的情况下必须使用CSS表达式

+1

除IE6和移动浏览器外。 – mercator 2010-12-16 17:00:49

+0

它必须在所有浏览器中运行,javascript解决方案被接受 – asker 2010-12-16 18:10:10

+1

您不必过于担心ie6 ...现在已被认为已经死了很长时间 – Kasturi 2010-12-16 18:31:48

-3
margin-left: -half_of_the_div; 
left: 50%; 
position: fixed; 

example on codepen

+1

您提供的答案已经成为问问者问题的一部分。核实。 – otherDewi 2013-11-05 19:25:41

8

由于CSS的calc()是现在,这里的解决方案使用calc()所有浏览器都支持。

#main { 
    width: 140px; 
    height:100px; 
    border: 1px solid Black; 
    text-align: left; 
    position: absolute; 
    top: calc(50vh - (/* height */100px/2)); 
    left: calc(50vw - (/* width */140px/2)); 
} 
+0

没有意识到这一点,这正是我需要这个案件 - 伟大的建议@罗伯特哈恩。 – kyleturner 2015-12-03 15:36:06

18

使用下面的CSS:

.centered { 
    position: fixed; 
    top: 50%; 
    left: 50%; 
    /* bring your own prefixes */ 
    transform: translate(-50%, -50%); 
} 
+0

迄今为止最优雅的解决方案..适用于所有尺寸和比例的所有盒子,无需定制。它跨浏览器兼容吗? – Gautam 2016-12-01 05:11:49

+0

这对元素的大小及其中的内容有着奇怪的影响。例如没有剩下:50%的元素会占用尽可能多的宽度空间,但剩下的只剩下50%:元素会变成魔术般的大小,并将内容分成多行。 – momomo 2017-05-31 17:51:43

0

复杂一点的方法是使用多外箱。这种方法有或没有中间有空格的硬编码的宽度/高度效果很好(背景颜色添加只是为了显示每箱做什么):

/* content of this box will be centered horizontally */ 
 
.boxH 
 
{ 
 
    background-color: rgba(0, 127, 255, 0.2); 
 
    width: 100%; 
 
    height: 100%; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    display: flex; 
 
    flex-direction: column; 
 
    align-items: center; 
 
} 
 

 
/* content of this box will be centered vertically */ 
 
.boxV 
 
{ 
 
    background-color: rgba(255, 0, 0, 0.2); 
 
    height: 100%; 
 
    display: flex; 
 
    flex-direction: row; 
 
    align-items: center; 
 
} 
 

 
/* content of this box will be centered horizontally and vertically */ 
 
.boxM 
 
{ 
 
    background-color: lightblue; 
 
    padding: 3em; 
 
}
<div> 
 
    some text in the background 
 
</div> 
 
<div class="boxH"> 
 
    <div class="boxV"> 
 
    <div class="boxM"> 
 
     this div is in the middle 
 
    </div> 
 
    </div> 
 
</div>

https://jsfiddle.net/vanowm/7cj1775e/

如果你想不管滚动位置如何,在中间显示div,然后将position更改为fixed