zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

CSS 实现水平和垂直居中的三种方法

2023-03-07 09:42:53 时间
  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;
}

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