欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

搞定!三种简单方法教你用 CSS 实现元素的水平垂直居中

最编程 2024-02-13 08:27:32
...
  1. 绝对定位 + 负边距:使用绝对定位并设置左右负边距和上下负边距,就可以实现水平和垂直居中的效果。
.center-element {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
  1. flex 布局:使用 flex 布局可以轻松实现水平和垂直居中。
.center-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}
  1. grid 布局:使用 grid 布局也可以实现水平和垂直居中。
.center-container {
  display: grid;
  place-items: center;
}

这些方法都可以实现水平和垂直居中的效果,您可以根据需要选择一种方法使用。