Fork me on GitHub

css div居中显示的4种写法

Demo:http://www.feman.cn/h5/center.html

 

1.absolute 绝对定位 这是我们最常用的一种居中定位写法 要求必须确定div的宽高度 目前市面上的浏览器基本上都支持这种写法

复制代码
<html lang="en">
    <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 class="absoluteCenter">我是absolute居中定位</div>
    </body>
    </html>
复制代码

2.translate定位 这是css3 transform的属性 通过自身的偏移来定位 而且他有个极大的好处 不需要知道div的宽高度 就像js里的this self一样 可以将宽高度设为百分比 IE browser<IE9不支持 在移动端使用较好

复制代码
<!doctype html>
    <html lang="en">
    <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 class="translateCenter">我是translate居中定位</div>
    </body>
    </html>
复制代码

 3.margin居中定位  不需要确定div的宽高度 让top,bottom,left,right都为0 再加个margin:auto 神来之笔 IE browser< IE 8不支持

复制代码
<!doctype html>
    <html lang="en">
    <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 class="marginCenter">我是margin居中定位</div>
    </body>
    </html>
复制代码

4.fixed的居中定位 这个用的最多的可能就是导航条这块儿 让导航条居中显示不随页面滚动

复制代码
<!doctype html>
    <html lang="en">
    <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 class="fixedCenter">我是fixed居中定位</div>
    </body>
    </html> 
复制代码
posted @   飞河  阅读(41772)  评论(2编辑  收藏  举报
编辑推荐:
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
· .NET 原生驾驭 AI 新基建实战系列:向量数据库的应用与畅想
· 从问题排查到源码分析:ActiveMQ消费端频繁日志刷屏的秘密
· 一次Java后端服务间歇性响应慢的问题排查记录
阅读排行:
· 互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(四):结合BotSharp
· Vite CVE-2025-30208 安全漏洞
· 《HelloGitHub》第 108 期
· MQ 如何保证数据一致性?
· 一个基于 .NET 开源免费的异地组网和内网穿透工具
Fork me on GitHub
点击右上角即可分享
微信分享提示