CSS 页面元素的居中有多种方法,常用的有以下几种:

1.使用 Flexbox 布局:

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

2.使用 Grid 布局:

#parent {
  display: grid;
  place-items: center;
}

3.使用 Grid Layout 和 Grid Template Columns 和 Grid Template Rows:

#parent {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
  grid-column: 2/3;
  grid-row: 2/3;
}

4.使用 CSS Grid 布局和 Grid Template Columns 和 Grid Template Rows:

#parent {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(3, 1fr);
}
#child {
  grid-column: 2/3;
  grid-row: 2/3;
}

5.使用 CSS Grid 布局和 Grid Template Areas:

#parent {
  display: grid;
  grid-template-areas: ". . ." ". mydiv ." ". . .";
}

6.使用 position 属性和 transform 属性:

#parent {
  position: relative;
}

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

7.使用 text-align 和 line-height 属性:

#parent {
  text-align: center;
}
#child {
  display: inline-block;
  line-height: 300px; /* 高度值 */
}

8.仅水平居中:

#mydiv {
  margin: 0 auto;
  width: 200px; /* 元素宽度 */
}

9.仅垂直居中:

#mydiv {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

10.使用 Table 布局:

#mydiv {
  display: table;
  margin: 0 auto;
}

11.使用 absolute 定位和 calc() 函数:

#mydiv {
  position: absolute;
  top: calc(50% - 150px); /* 高度的一半 */
  left: calc(50% - 150px); /* 宽度的一半 */
  width: 300px; /* 自身宽度 */
  height: 300px; /* 自身高度 */
}

这些方法中有些需要父元素支持,如 Flexbox 布局和 Grid布局需要在父元素上添加相应的布局。