插件窝 干货文章 如何在 CSS 中将 Div 居中

如何在 CSS 中将 Div 居中

class position div relative 759    来源:    2024-10-20

弹性盒:

.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

网格

.container {
  display: grid;
  place-items: center;
  height: 300px;
}

弹性保证金

.container {
  display: flex;
  height: 300px;
}
.centered-div {
  margin: auto;
}

绝对定位

.container {
  position: relative;
  height: 300px;
}
.centered-div {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

自动保证金

.container {
  height: 300px;
}
.centered-div {
  width: 200px;
  margin: 0 auto;
  position: relative;
  top: 50%;
  transform: translatey(-50%);
}

网格模板

.container {
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  grid-template-rows: 1fr auto 1fr;
  height: 300px;
}
.centered-div {
  grid-column: 2;
  grid-row: 2;
}