发布于 2025-12-07 0 阅读
0

在 CSS 中使对象居中的最佳方法(水平和垂直)

在 CSS 中使对象居中的最佳方法(水平和垂直)

在本文中,我将向您展示如何通过三种不同的方式在 CSS 中水平和垂直居中对象。

第一:

.parent {
  display: flex;
  align-items: center;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

第二:

IE 不支持此方式

.parent {
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

第三:

.parent {
  position: relative;
}
.child {
  position: absolute;
  transform: translate(-50%,-50%);
  left: 50%;
  top: 50%;
}
Enter fullscreen mode Exit fullscreen mode

第四:

@mrdanielschwarz提及

.parent {
  display: flex or grid;
  height: 100vh;
}
.child {
  margin: auto;
}
Enter fullscreen mode Exit fullscreen mode

您更喜欢哪种方式?您知道其他方式吗?

文章来源:https://dev.to/amirjafari1992/best-ways-to-center-objects-in-css-5558