居中

来源:互联网 发布:淘宝专业刷信誉 编辑:程序博客网 时间:2024/04/30 22:36

众所周知最常用的居中方式margin:auto却只能用于水平居中,要实现垂直居中,还得添加更多的属性。以下列出一些常见的垂直居中的方法,当然并不全面,不过也算够用。

1.绝对定位

        .center{            width: 200px;height: 200px;            position: absolute;            top: 0;left: 0;right: 0;bottom: 0;            margin: auto;        }
  • 优点:

    • 兼容IE8+
    • 代码量少,只用一个元素就能实现
    • 完美支持图片居中
    • 支持百分比%属性值和min-/max-属性
  • 缺点:

    • 必须给出高度;
    • 最好设置overflow:auto属性防止内容溢出
    • 在Windows Phone上不起作用

2.负外边距

        .center{            width: 200px;height: 200px;            position: absolute;            top: 50%;            left: 50%;            margin-left: -100px;  /* (width + padding)/2 */            margin-top: -100px;  /* (height + padding)/2 */          }
  • 优点

    • 可兼容IE6+,代码量少
  • 缺点:

    • 不能自适应,内容可能溢出容器
    • 需设置高宽,且不支持百分比尺寸和min-/max-属性设置。

3.Thransforms 变形

        .center{            position: absolute;            top: 50%;            left: 50%;            -webkit-transform: translate(-50%,-50%);            -ms-transform: translate(-50%,-50%);            transform: translate(-50%,-50%);        }
  • 特点:高度可变,支持IE9+,transform必须带上浏览器厂商的前缀, 可能干扰其他transform效果

4.表格单元格(table-cell)

        .table-cell{            width: 800px;height: 800px;            display: table-cell;            vertical-align: middle;        }
  • 特点:支持IE8+,且.table-cell是高宽确定的父元素

5.Flexbox布局

方法一:

        .outer{            height: 800px;            display: flex;            align-items: center;            justify-content: center;        }        .center{            width: 12em;            height: 8em;        }

方法二:

        .outer{            display: flex;            height: 800px;        }        .center{            margin: auto;        }
  • 特点:支持IE10+,且方法二中必须设置高宽才能在IE中居中
0 0
原创粉丝点击