”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何在 CSS 中将 Div 居中

如何在 CSS 中将 Div 居中

发布于2024-11-08
浏览:253

ow to Center a Div in CSS

弹性盒:

.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;
}
版本声明 本文转载于:https://dev.to/hahaxo/2024how-to-center-a-div-in-css-2hjj?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3