我想将具有绝对位置的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;
}
Run Code Online (Sandbox Code Playgroud)
Kas*_*uri 48
换position:absolute
到position: fixed
,你应该好好去!
当你说position - absolute时,引用div是具有位置 - 相对的父div.但是,如果你说position -fixed,那么引用就是浏览器的窗口.这是你想要的wat.
在IE6的情况下,我猜你必须使用CSS表达式
小智 40
使用以下CSS:
.centered {
position: fixed;
top: 50%;
left: 50%;
/* bring your own prefixes */
transform: translate(-50%, -50%);
}
Run Code Online (Sandbox Code Playgroud)
Bas*_*der 20
如果您不想将元素的位置更改为fixed
,则这是一个保留元素的解决方案absolut
.
由于calc()
现在所有浏览器都支持CSS ,这里有一个解决方案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));
}
Run Code Online (Sandbox Code Playgroud)
margin
这是使用和 的解决方案position: fixed
:
#main{
width: 140px;
height:100px;
border: 1px solid black;
/* Centering #main on the screen */
position: fixed;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
Run Code Online (Sandbox Code Playgroud)
它div
通过增加margin
所有边的 来使 居中以适合整个屏幕。
编辑:我发现有一个简写top,right,bottom,left
是inset
。它已经在主流浏览器中实现,您可以在这里查看其他浏览器的兼容性
因此,要使 div 在屏幕上绝对居中:
#main{
width: 140px;
height:100px;
border: 1px solid black;
/* Centering #main on the screen */
position: fixed;
margin: auto;
inset: 0;
}
Run Code Online (Sandbox Code Playgroud)