css绝对居中

作者: ferrint | 来源:发表于2017-03-01 15:15 被阅读10次

** 关键词:**绝对居中

css实现居中有很多方法,在这里我罗列出来三种:

  • 第一种
  • 优点:兼容性好
  • 缺点:必须知道宽高,修改不方便,(可以用sass定义变量)
 .element {
    width: 600px; height: 400px;
    position: absolute; left: 50%; top: 50%;
    margin-top: -200px;    /* 高度的一半 */
    margin-left: -300px;    /* 宽度的一半 */
  }
  • 第二种
  • 优点:利用css3,不用知道宽高,响应式布局
  • 缺点 : IE9以下不兼容
 .element {
    width: 600px; height: 400px;
    position: absolute; left: 50%; top: 50%;
    transform: translate(-50%, -50%);    /* 50%为自身尺寸的一半 */
  }
  • 第三种
  • 优点:兼用性好,响应式布局
    .element {
        width: 600px; height: 400px;
        position: absolute; left: 0; top: 0; right: 0; bottom: 0;
        margin: auto;    /* 有了这个就自动居中了 */
    }

相关文章

网友评论

    本文标题:css绝对居中

    本文链接:https://www.haomeiwen.com/subject/aiaqgttx.html