css垂直水平居中

2021-05-25  本文已影响0人  jack_rofer

一。设置在父元素:(flex,grid)

  1. display:flex (ie11)【推荐-兼容性好些】
.father{
  width: 500px; // 得设置宽高呀
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid pink;
}
.center{
  border: 1px solid pink;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%)
}
  1. display: grid(不支持ie)
.father{
  width: 500px; // 得设置宽高呀
  height: 500px;
  display: grid;
  justify-content: center;
  align-items: center;
  border: 1px solid pink;
}
.center{
  border: 1px solid pink;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%)
}

二。设置在自身:(absolute)

  1. transfrom:translate(ie9+)【推荐-不用设置宽高】
    绝对定位元素的偏移属性和translate()函数
.father{
  position: relative; //最好设置一下父元素
}
.center{
  border: 1px solid pink;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%)
}
  1. margin: auto (兼容性好)
    绝对定位元素的盒模型特性,在偏移属性为确定值的基础上,设置margin:auto
.father{
  position: relative; //最好设置一下父元素
}
.center{
  border: 1px solid pink;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  width: 500px;  //必须设置宽高
  height: 500px;
}

三。父元素子元素都要设置:(table-cell)

  1. margin + vertical-align
    父元素 display: table-cell 子元素display: table 还要设置宽高(!!!恶心,但兼容性好呀)(ie7)
.father{
  display: table-cell;
  vertical-align: middle;
  width: 500px;
  height: 500px;
  border: 1px solid red;
}
.center{
  display: table;
  margin: 0 auto;
  width: 100px;
  height: 100px;
  border: 1px solid pink;
}
  1. text-align + vertical-align【推荐-子元素不用设置为table】
    在父元素设置text-align和vertical-align,并将父元素设置为table-cell元素,子元素设置为inline-block元素
.father{
  display: table-cell;
  vertical-align: middle;
  text-align: center;
  width: 500px;
  height: 500px;
  border: 1px solid red;
}
.center{
  display: inline-block;
  width: 100px;
  height: 100px;
  border: 1px solid pink;
}

四。文本垂直居中(text-align,line-height)

text-align + line-height
实现单行文本水平垂直居中

.center{
  text-align: center;
  line-height: 50px;
  width: 100px;
  height: 50px;
  border: 1px solid pink;
}
上一篇下一篇

猜你喜欢

热点阅读