当前位置:Gxlcms > html代码 > css+div水平居中的实例代码

css+div水平居中的实例代码

时间:2021-07-01 10:21:17 帮助过:8人阅读

实现div内容水平居中

实现方案一:margin:0 auto;

  1. div{
  2. height:100px;
  3. width:100px;
  4. background:red;
  5. margin:0 auto;
  6. }

  

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>div水平居中</title>
  6. </head>
  7. <body>
  8. <div></div>
  9. </body>
  10. </html>

  

实现div水平居中方案二:position:absolute;绝对定位

  1. div{height:100px;width:100px;background:red;position:absolute;
  2. left:50%;
  3. right:50%;
  4. margin: auto;
  5. }

实现div水平垂直居中

实现方案一:position:fixed;固定定位

  1. div{height:100px;width:100px;background:red;position:fixed;left:0;top:0;bottom:0;right:0;margin:auto;
  2. }

实现方案二:position:absolute;绝对定位

  1. div{height:100px;width:100px;background:red;position:absolute;left:0;top:0;bottom:0;right:0;margin:auto;
  2. }

实现方案二:css3+position;

  1. div{height:100px;width:100px;background:red;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
  2. }

transform为css3的新增属性,因此需要加上前缀,兼容手机和其他的浏览器。如

  1. -ms-transform:translate(-50%,-50%); /* IE 9 */-moz-transform:translate(-50%,-50%); /* Firefox */-webkit-transform:translate(-50%,-50%);/* Safari and Chrome */-o-transform:translate(-50%,-50%); /* Opera */

以上就是css+div水平居中的实例代码的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行