我应该使用margin 0 auto还是position、top、left来将内容居中对齐?

3

我想知道如何将内容水平垂直居中,使用“margin”属性是否最好?还是应该使用position: absolute和top、left属性?使用其中之一有什么优缺点?


1
你能试试这个吗?(https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/) - William Ku
1个回答

2

使用此方法(当您知道要居中的内容的大小)-

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
}

或者这样做(当您不知道要居中的元素的大小)-

.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  /* bring your own prefixes */
  transform: translate(-50%, -50%);
}

来源: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/

这是一篇关于如何将对象完全居中的 CSS 技巧。要实现这个目标,我们需要使用绝对定位和 transform 属性。首先,将对象设为绝对定位。接着,利用 transform 属性的 translate(-50%,-50%) 选项将对象上下左右移动到它应该在的位置。这个技巧可以适用于任何尺寸和形状的对象,无需知道其精确尺寸或位置。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接