CSS之居中布局的实现方法
                (编辑:jimmy 日期: 2025/11/4 浏览:3 次 )
            
            
            在前端开发中,我们经常会遇到各种上不同场景的关于居中的布局,一般水平居中是相对简单,而 垂直居中与水平垂直则相应要麻烦些。在下来我们对各种场景一一列出解决方案。
水平居中
水平居中相对于其它几中居中排列要简单的多,按标签元素可分为行内元素与块级元素居中:
1、行内元素
如:a img span em b small 此类标签元素及文本
 .center { text-align: center; }
2、块级元素
如:div section header p此类标签元素,需要设置宽度
.center { margin: 0 auto; }
垂直居中
1、line-height
针对有且仅有一行内容时可行。将line-height值设为相对应高度即可。
2、vertical-align
针对行内元素如img span等元素,其对齐相对于文本基线。达不到完美的垂直居中,不常用。
3、其它
关于垂直居中其它方式参考水平垂直居中。
水平垂直居中
在水平垂直居中的场景中,可分为定宽定高、不定宽不定高,按不同应用场景可分如下几种方式,在布局中实际情况而定。
1、Flex方式
适用场景:IE9+、现代浏览器、响应式、不定宽不定高
<section class="center">
    <div>水平垂直居中</div>
</section>
.center {
    display: flex;
    justify-content: center;
    align-items: center;
}
2、绝对定位方式
适用场景:IE8+、及现代浏览器、响应式
<section class="center">
    水平垂直居中
</section>
.center {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
}
3、绝对定位+transform方式
适用场景:IE9+、及现代浏览器、响应式、不定宽不定高
<section class="center">
    水平垂直居中
</section>
.center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%)
}
4、绝对定位+calc函数
适用场景:IE9+、及现代浏览器、定宽定高
<section class="center">
    水平垂直居中
</section>
.center {
  width: 200px;
  height: 200px;
  position: absolute;
  top: calc(50% - 100px);
  left: calc(50% - 100px);   
}
5、绝对定位+margin负属性
适用场景:IE6+、及现代浏览器、定宽定高
<section class="center">
    水平垂直居中
</section>
.center {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 200px;
    height: 200px;
    margin-left: -100px;
    margin-top: -100px;
}
6、Table-cell方式
适用场景:IE8+、及现代浏览器、不定宽不定高
<div class="table">
  <div class="table-cell">
    <div class="center-content">
      水垂直居中
    </div>
  </div>
</div>
.table{ display: table; }
.table-cell {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}
.center-content{
  width: 50%;
  margin: 0 auto;
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
下一篇:css魔法之左边竖条的多种实现方法