CSS 各种居中方式

CSS里有很多种居中的方式,自己整理了一些常见的居中方式

水平居中

  • 行内元素水平居中

给行内元素的父级加 text-align:center;

.container{
    text-align:center;
}
  • 已知块级元素的宽水平居中

设置左右marign的值为auto

.container{
    width:600px;
    margin:0 auto;
}

垂直居中

  • 行内元素设置行高和父级高度一样

行内的line-height的值和父级的高度相等就可以垂直居中

.container{
  height:200px;
  border:1px solid #000;
  text-align:center;
}

.center{
  line-height:200px;
}
  • 不知道父级的高度垂直居中

将上下padding的值相等

.container{
  border:1px solid #000;
  text-align:center;
}

.center{
  display:inline-blcok;
  padding:20px 0;
}
  • display:table-cell

设置display的值为table-cell,将元素变为表格cell显示

.container{
  border:1px solid #000;
  width:600px;
  height:800px;
  display:table-cell;
  vertical-align:middle;
  text-align:center;
}
  • 添加伪元素实现居中

这个方法比较特别

.container{
  border:1px solid #000;
  width:600px;
  height:800px;
  text-align:center;
}

.container::before{
  width:0;
  height:800px;
  content:'';
  display:inline-block;
  vertical-align:middle;
}

水平垂直居中

  • 绝对定位

父元素 postion 为 relative 子元素 position 为absolute ,用 transform 属性居中

.container{
  position:relative;
  width:800px;
  height:800px;
  border:1px solid #000;
}

.center{
  position:absolute;
  border:1px solid #000;
  width:100px;
  height:100px;
  top:50%;
  left:50%;
  transform:translate(-50%,-50%)
}
  • 用flex布局

目前的主流方式,非常好用,建议用这种

.container{
  width:800px;
  height:800px;
  border:1px solid #000;
  display:flex;
  align-items: center;
  justify-content: center;
}

.center{
  width:100px;
  height:100px;
  border:1px solid #000;
}
  • grid布局

较新的方法,所以有兼容问题,未来会越来越常使用

.container{
  width:800px;
  height:800px;
  border:1px solid #000;
  display: grid;
  align-items: center;
  justify-content: center;
}

.center{
  width:100px;
  height:100px;
  border:1px solid #000;
}
原文地址:https://www.cnblogs.com/ianyanyzx/p/9930464.html