【问题标题】:Divs 'left / center / right' - how to perfectly center without 'width'?Divs 'left / center / right' - 如何在没有'宽度'的情况下完美居中?
【发布时间】:2015-08-07 02:36:37
【问题描述】:

这个问题是基于这个答案:https://stackoverflow.com/a/23876839/994141

我阅读了很多关于这个主题的主题,在我看来这似乎是最好的答案,因为我想避免设置 width
但是居中的内容不是很好居中,而是基于左右两边的内容。
证明: https://jsfiddle.net/p7kfuont/('b' 不在第一行居中)

有没有办法在不设置widths 的情况下改进这段代码(inline-blockfloat)?

【问题讨论】:

  • 什么可以帮助您不指定宽度?

标签: css css-float center


【解决方案1】:

这是你想要达到的目标吗?

.container {
    display: table;
    table-layout: fixed;
    border-collapse: collapse;
    width: 100%;
    text-align: center;
}
.container > div {
    display: table-cell;
    border: 1px solid red;
}
<div class="container">
    <div class="left">aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</div>
    <div class="center">b</div>
    <div class="right">c</div>
</div>
<div class="container">
    <div class="left">a</div>
    <div class="center">b</div>
    <div class="right">c</div>
</div>

【讨论】:

    【解决方案2】:

    如果您希望 b 严格在中间,您可以添加:

        .container {
          position: relative;
        }
    
        .container .center {
          position: absolute;
          left: 50%;
          transform: translateX(-50%); /*add this if you want the element centered*/
          -ms-transform: translateX(-50%); /* IE 9 */
          -webkit-transform: translateX(-50%); /* Chrome, Safari, Opera */
        }
    

    transform: translateX(-50%) 会将元素的中心设置在中心,而没有它,您的元素的左边缘将位于中心。

    jsFiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      • 2014-10-22
      • 1970-01-01
      • 2016-08-30
      • 2021-12-27
      • 2012-04-17
      相关资源
      最近更新 更多