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> 

转载于:https://www.cnblogs.com/leinov/p/4073794.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值