CSS居中對齊

https://css-tricks.com/center...
https://segmentfault.com/a/11...

水平居中

子元素爲行內元素

.center-children {
  text-align: center;
}

子元素爲塊級元素

.center-me {
  margin: 0 auto;
}

多個塊級子元素

.inline-block-center {
  text-align: center;
}
.inline-block-center div {
  display: inline-block;
  text-align: left;
}
.flex-center {
  display: flex;
  justify-content: center;
}

垂直居中

單行子元素

.link {
  padding-top: 30px;
  padding-bottom: 30px;
}
.center-text-trick {
  height: 100px;
  line-height: 100px;
  white-space: nowrap;  //空格不換行
}

多行子元素

.center-table {
  display: table;
}
.center-table p {
  display: table-cell;
  vertical-align: middle;
}
.flex-center-vertically {
  display: flex;
  justify-content: center;
  flex-direction: column;
  resize: vertical;  //可變換大小
}
.ghost-center {
  position: relative;
}
.ghost-center::before {
  content: " ";
  display: inline-block;
  height: 100%;
  width: 1%;
  vertical-align: middle;
}
.ghost-center p {
  display: inline-block;
  vertical-align: middle;
}

塊級子元素

知道子元素高度

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */
}

不知道子元素高度

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
.parent {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

水平垂直居中

知道子元素的寬高

.parent {
  position: relative;
}

.child {
  width: 300px;
  height: 100px;
  padding: 20px;

  position: absolute;
  top: 50%;
  left: 50%;

  margin: -70px 0 0 -170px;
}

子元素的沒有固定的寬高

.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}
body, html {
  height: 100%;
  display: grid;
}
span {
  margin: auto;
}
相關文章
相關標籤/搜索