【问题标题】:Why do we have to set a width with margin : 0 auto when horizontally centering a div? [duplicate]为什么我们必须在水平居中 div 时设置一个带边距的宽度:0 auto? [复制]
【发布时间】:2023-03-28 17:55:01
【问题描述】:

为什么我们在使用margin:0 auto; 来水平居中一个 div 时必须使用设置的宽度?

【问题讨论】:

  • 你不必这样做,除非你试图将元素水平居中。
  • 边距:0 自动;表示上下边距为 0,而左右边距为自动。 “auto”与 0 无关。
  • 因为如果没有宽度,那么宽度就是100%,不能居中。

标签: css margin centering


【解决方案1】:

如果元素是display: block,并且您没有设置宽度,则元素将stretch horizontally to fit its containing block,导致自动边距归零(从技术上讲,这算作元素居中,因为两个自动边距都解决了到一个相等的零值)。

【讨论】:

  • 我的错,我忘了指定关于水平居中的 div
  • @Radioreve,答案还是正确的。
猜你喜欢
  • 2015-05-29
  • 2017-11-29
  • 1970-01-01
  • 2014-04-08
  • 2023-02-13
  • 1970-01-01
  • 2013-01-31
  • 2015-06-24
  • 2017-05-18
相关资源
最近更新 更多