css中position:fixed实现div在窗口上下左右居中

建站知识 2021-07-03 08:15www.168986.cn长沙网站建设
上下左右 居中

代码如下

复制代码
代码如下:

div{
position:fixed;
margin:auto;
left:0;
right:0;
top:0;
bottom:0;
width:200px;
height:150px;
}

如果只需要左右居中,那么把 bottom:0; 或者 top:0; 删掉即可
如果只需要上下居中,那么把 left:0; 或者 right:0; 即可

狼蚁网站SEO优化附一个DIV 元素在浏览器窗口居中

其实,实现这个效果并不复杂,利用 CSS 中的 position 定位就可以轻松搞定了。来看看代码吧:

代码如下

复制代码
代码如下:

<style type="text/css">
.dialog{
position: fixed;
_position:absolute;
z-index:1;
top: 50%;
left: 50%;
margin: -141px 0 0 -201px;
width: 400px;
height:280px;
border:1px solid #CCC;
line-height: 280px;
text-align:center;
font-size: 14px;
background-color:#F4F4F4;
overflow:hidden;
}
</style>
<div class="dialog">我是在窗口正中央的,呵呵!</div>

设置的技巧全部在这里:

代码如下

复制代码
代码如下:

.dialog{
position: fixed;
_position:absolute; /* hack for IE6 */
z-index:1;
top: 50%;
left: 50%;
margin: -141px 0 0 -201px;
width: 400px;
height:280px;
border:1px solid #CCC;
line-height: 280px;
text-align:center;
font-size: 14px;
background-color:#F4F4F4;
overflow:hidden;
}

设置 position: fixed; _position:absolute;
设置 left:50% 和 top:50%;
设置 margin: -(DIV的offsetWidth/2) 0 0 -(DIV的offsetHeight/2)

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by

长沙网络推广|微博营销|长沙seo优化|视频营销|长沙网络营销|微信营销|长沙网站建设|口碑营销|软文营销