本文摘自PHP中文网,作者coldplay.xixi,侵删。
css div居中显示的方法:1、使用absolute绝对定位,代码为【
absolute居中定位】;2、使用translate定位;3、使用margin居中定位;4、使用fixed的居中定位。

本教程操作环境:windows7系统、css3版,DELL G3电脑。
css div居中显示的方法:
1、absolute 绝对定位 这是我们最常用的一种居中定位写法 要求必须确定div的宽高度 目前市面上的浏览器基本上都支持这种写法
1 2 3 4 5 6 7 8 9 10 11 12 13 | <html>
<head>
<meta charset= "UTF-8" >
<title>absolute居中定位</title>
<style>
*{margin:0;padding:0}
.absoluteCenter{ width:600px; height:400px;position:absolute; background: rgb(50,183,97); left:50%; top:50%; margin-left: -300px; margin-top: -200px; }
</style>
</head>
<body>
<div>我是absolute居中定位</div>
</body>
</html>
|
2、translate定位 这是css3 transform的属性 通过自身的偏移来定位 而且他有个极大的好处 不需要知道div的宽高度 就像js里的this self一样 可以将宽高度设为百分比 IE browser<IE9不支持 在移动端使用较好
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!doctype html>
<html>
<head>
<meta charset= "UTF-8" >
<title>translate居中定位</title>
<style>
*{margin:0;padding:0}
.translateCenter{ width: 40%; height: 20%; position: absolute; left:50%; top:50%; transform:translate(-50%,-50%); background: #2d2d2d;}
</style>
</head>
<body>
<div>我是translate居中定位</div>
</body>
</html>
|
3、margin居中定位 不需要确定div的宽高度 让top,bottom,left,right都为0 再加个margin:auto 神来之笔 IE browser< IE 8不支持
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!doctype html>
<html>
<head>
<meta charset= "UTF-8" >
<title>margin居中定位</title>
<style>
*{margin:0;padding:0}
.marginCenter{ width:200px; height: 200px; position: absolute;left:0; top:0; right:0; bottom: 0; margin: auto; background: #f2056e;}
</style>
</head>
<body>
<div>我是margin居中定位</div>
</body>
</html>
|
4、fixed的居中定位 这个用的最多的可能就是导航条这块儿 让导航条居中显示不随页面滚动
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <!doctype html>
<html>
<head>
<meta charset= "UTF-8" >
<title>fixed居中定位</title>
<style>
*{margin:0;padding:0}
.fixedCenter{max-width:980px; height:70px; position:fixed; margin:0 auto; left:0; right:0; background:rgb(67,163,244);}
</style>
</head>
<body>
<div>我是fixed居中定位</div>
</body>
</html>
|
相关教程推荐:CSS视频教程
以上就是css div如何居中显示的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
css怎么设置透明度的颜色
如何实现css代码复用
css column-gap属性怎么用
jquery怎么获取name
css如何取消样式
css中keyframes是什么意思
你可能还不知道的7个惊人的css属性!
css如何实现始终将footer固定在底部
利用css来画出各种样式不同的梯形
jquery如何动态添加删除css样式?(代码示例)
更多相关阅读请进入《css》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » css div如何居中显示