如何在 CSS 中将 Div 居中

如何在 css 中将 div 居中

弹性盒:

.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;
}

以上就是如何在 CSS 中将 Div 居中的详细内容,更多请关注www.sxiaw.com其它相关文章!