CSS(二)块元素水平垂直居中总结

277 阅读1分钟

一、宽高固定

公共样式

.f {
    position: relative;
    height: 60px;
    width: 60px;
}
.s {
    position: absolute;
    height: 20px;
    width: 20px;
    line-height: 20px;
    text-align: center;
}

1. absolute + 负 margin

.f1 {
  background-color: blue;
}
.s1 {
  top: 50%;
  left: 50%;
  margin-top: -10px;
  margin-left: -10px;
  background-color: pink;
}

2. absolute + margin:auto

.f2 {
  background-color: yellow;
}
.s2 {
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  background-color: skyblue;
}

3. absolute + calc

.f3 {
  background-color: red;
}
.s3 {
  background-color: white;
  top: calc(50% - 10px);
  left: calc(50% - 10px);
}

二、宽高不固定

1. absolute + transform

.f4 {
  position: relative;
  height: 60px;
  width: 60px;
  background-color: #bfa;
}
.s4 {
  position: absolute;
  background-color: sandybrown;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

2. flex

.f5 {
  display: flex;
  height: 60px;
  width: 60px;
  background-color: rgb(235, 103, 195);
  justify-content: center;
  align-items: center;
}
.s5 {
  background-color: aqua;
}

3. grid

.f6 {
  display: grid;
  height: 60px;
  width: 60px;
  background-color: rgb(92, 228, 183);
}
.s6 {
  align-self: center;
  justify-self: center;
  background-color: snow;
}

4. table

.f7 {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
  height: 60px;
  width: 60px;
  background-color: orange;
}
.s7 {
  display: inline-block;
  background-color: gainsboro;
}

三、总结

方法 宽高固定? PC兼容性 移动端兼容性
absolute + 负margin 固定 ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
absolute + margin auto 固定 ie6+, chrome4+, firefox2+ 安卓2.3+, iOS6+
absolute + calc 固定 ie9+, chrome19+, firefox4+ 安卓4.4+, iOS6+
absolute + transform 不固定 ie9+, chrome4+, firefox3.5+ 安卓3+, iOS6+
flex 不固定 ie10+, chrome4+, firefox2+ 安卓2.3+, iOS6+
grid 不固定 ie10+, chrome57+, firefox52+ 安卓6+, iOS10.3+
css-table 不固定 ie8+, chrome4+, firefox2+ 安卓2.3+, iOS6+