CSS 居中方案

1,水平居中

a)父級 text-align + 子級 inline-block 或 inline

.parent {
  text-align: center;
}
.child {
  display: inline-block;
}

b)將元素塊狀化 + margin

/* display: table 也可以 */
.element {
  display: block;
  margin: 0 auto;
}

c)父級 relative + 子級 absolute 和 transform

.parent {
  position: relative;
}
.child {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

d)父級 flex + justify-content

.parent {
  display: flex;
  justify-content: center;
}

2,垂直居中

a)父級 table-cell + vertial-align

.parent {
  display: table-cell;
  vertical-align: middle;
}

b)父級 relative + 子級 absolute 和 transform

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

c)父級 flex + align-items

.parent {
  display: flex;
  align-items: center;
}

3,水平垂直居中

a)inline-block + table-cell + text-align + vertical-align

.parent {
  text-align: center;
  display: table-cell;
  vertical-align: middle;
}
.child {
  display: inline-block;
}

b)父級 relative + 子級 absolute 和 transform

.parent {
  position: relative;
}
.child {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

c)flex

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

d)《css世界》中張鑫旭大神提供的一種寫法

/* 寬高、定位、top、left、right、bottom、margin 缺一不可 */
.parent {
  width: 300px;
  height: 300px;
  position: relative;
}
.child {
  width: 100px;
  height: 100px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章