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;
}
    原文作者:jh2k15
    原文地址: https://segmentfault.com/a/1190000012113553
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞