- 发表于 2018-03-08
- 最后更新于 2018-03-08
- 阅读次数 
- 标签:
CSS 的居中一直让人诟病,尤其是面对浏览器兼容问题的时候,
本系列将分别搜集主流的 CSS 水平居中、垂直居中、水平垂直居中方法及其兼容性。第一篇介绍 CSS 水平居中。
假设HTML结构类似:
| 12
 3
 
 | <div class="parent"><div class="content">Center Element</div>
 </div>
 
 | 
行内元素或行内块元素
| 12
 3
 
 | .content {text-align: center;
 }
 
 | 
兼容性:IE 3+
固定宽度元素
| 12
 3
 4
 
 | .content{width: 200px;
 margin: 0 auto;
 }
 
 | 
兼容性:IE 6+
自动宽度元素(通用解决方案)
呈现为表格
| 12
 3
 4
 
 | .content{display: table;
 margin: 0 auto;
 }
 
 | 
兼容性:IE 8+
呈现为行内块元素再对齐
利用display: inline-block将其呈现为行内块元素,再利用行内块元素的水平居中方法进行水平居中。
| 12
 3
 
 | .content {text-align: center;
 }
 
 | 
当该元素周围存在行内元素或行内块元素时,会导致其无法像块元素一样独占一行,此时需要在其外层再加一层div元素:
| 12
 3
 
 | <div class="parent"><div><div class="content">Center Element</div><div>
 </div>
 
 | 
兼容性:IE 8+
绝对定位
| 12
 3
 4
 5
 6
 7
 8
 
 | .parent {position: relative;
 }
 .content {
 position: absolute;
 left: 50%;
 transform: translateX(-50%);
 }
 
 | 
绝对定位带来的问题是:父元素无法自适应高度包裹其子元素,而且存在其它子元素的话会出现重叠,需要用margin等方法留出空位。
兼容性:IE 9+
Flex
| 12
 3
 4
 
 | .parent {display: flex;
 justify-content: center;
 }
 
 | 
兼容性:IE 10+(IE 10 需要前缀-ms-)
Grid
| 12
 3
 4
 5
 6
 
 | .parent {display: grid;
 }
 .content{
 margin: 0 auto;
 }
 
 | 
兼容性:IE 10+(IE 10 需要前缀-ms-)
The End
© 本文著作权归 vimcaw 所有,未经许可,不得转载使用。
推荐文章
Powered by hexo文章推荐插件