css div如何居中显示

发布时间:2021-03-11 14:40:18 作者:小新
来源:亿速云 阅读:147

这篇文章给大家分享的是有关css div如何居中显示的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

css div居中显示的方法:1、使用absolute绝对定位,代码为【absolute居中定位】;2、使用translate定位;3、使用margin居中定位;4、使用fixed的居中定位。

css div居中显示的方法:

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

<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不支持 在移动端使用较好

<!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不支持

<!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的居中定位 这个用的最多的可能就是导航条这块儿 让导航条居中显示不随页面滚动

<!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 div如何居中显示”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

推荐阅读:
  1. css怎样使文字垂直对齐
  2. css里面如何让body内容居中

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

css div

上一篇:MongoDB 中使用模式构建之属性模式的

下一篇:css中font字体颜色的设置方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》