【问题标题】:how to use margin:0 auto without setting width of inner div如何在不设置内部div宽度的情况下使用margin:0 auto
【发布时间】:2017-12-20 14:25:06
【问题描述】:

我尝试将宽度设置为自动,但也没有用。

<div style='width:100%;background-color:lightblue;text-align:center'>
test
<div style='margin:0 auto;background-color:blue;'>
new test
</div>
</div>

【问题讨论】:

  • 你想要的结果是什么?
  • 这将使 div 居中,但不指定宽度是不可能的,有无限可能。您可以将左右边距设置为某个值,如果它们相同,它将居中。
  • 我希望内部 div 的宽度等于字符“新测试”占用的空间宽度,但我现在明白了这个问题。我想我们可以计算文本的长度并将宽度设置为那个
  • @DCR 这个问题可能对你有帮助stackoverflow.com/questions/20383622/…

标签: html css


【解决方案1】:

使用inlineinline-block

<div style='width:100%;background-color:lightblue;text-align:center'>
test<br>
<div style='margin:0 auto;display:inline;background-color:blue;'>
new test
</div>
</div>

【讨论】:

  • 这是错误的,不是“display:inline”使这个居中,而是父 div 的“text-align:center”这样做。删除 text-align:center ,您将看到两个元素左对齐。将 display:inline 替换为 "width:100px;"并且“新测试”将弹回中心。
  • 正确的margin: 0 auto 可能不需要,但如果您设置宽度或删除display:inline,孩子将没有自动宽度
猜你喜欢
  • 2014-12-24
  • 2010-12-21
  • 2011-06-30
  • 2014-12-19
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
  • 2013-12-11
相关资源
最近更新 更多