【问题标题】:Center n-divs in row (Bootstrap)在行中居中 n-div (Bootstrap)
【发布时间】:2017-05-11 23:47:40
【问题描述】:

我有一个 Bootstrap 行,其中包含可变数量的 div,它们需要相对于它们的父行居中。到目前为止,html是这样设置的:

<div class="row proj-container">

    <div class="proj col-md-4 col-xs-12"></div>

</div>

我使用 javascript 克隆并在 .proj-container 中附加可变数量的 .proj。它工作正常,如果 .proj 超过 3 个,由于网格配置,它们会正确包裹到其他行上。 我无法实现的是这组 div 在其父级内部的居中。

  • 将“.text-center”分配给父级不起作用
  • 父级上的文本对齐和子级上的内联块不起作用
  • 使父级 flex 和 justify:space-around 实现居中子级,但会覆盖网格系统 (col-md-4),如果超过三个或在较小的设备上,它们将不会换行...

关于如何设置样式以实现 div 的居中和包装的任何想法?

【问题讨论】:

    标签: twitter-bootstrap centering


    【解决方案1】:

    这是另一种解决方案。看jsFiddle

    .proj {
      display: inline-block;
      height: 10px;
      border: 1px solid red;
      margin: 0 -2px;
      float: none;
    }
    

    HTML:

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="container-fluid">
      <div class="row proj-container text-center">
        <div class="proj col-md-4 col-xs-12"></div>
        <div class="proj col-md-4 col-xs-12"></div>
        <div class="proj col-md-4 col-xs-12"></div>
        <div class="proj col-md-4 col-xs-12"></div>
        <div class="proj col-md-4 col-xs-12"></div>
      </div>
    </div>
    

    【讨论】:

    • 你成功了,谢谢!我即使没有带有“container-fluid”的更多外部div,它也可以工作,而且“proj-container”上的“text-center”似乎是多余的。看起来像 inline-block 并且没有浮动在要居中的元素上有所不同。你能评论一下为什么吗?如果最后一行的 div 会粘在左边(如果小于 2),那也是完美的。我不知道这是否可能,但如果您有解决方案,请随时分享。再次感谢您!
    • 我认为text-center 会影响非浮动内联块元素。 float: none 不会将元素推送到任何边框(反对浮动左或右),因此非浮动内联元素可以在其父元素内对齐。
    【解决方案2】:

    您可以尝试以下使网格列居中的方法

    .project-container {
       text-align: center; /* set all inline elements to be centered */
    }
    
    .project-container .proj {
      display: inline-block; /* set the columns to inline blocks so they are centered */
      float: none;
    }
    

    【讨论】:

    • 谢谢,但正如我在问题中指定的那样,此解决方案不起作用。我不知道为什么即使如此显示,div 也不表现为内联元素。也许是因为它们本身包含一堆其他元素,但我不太确定......
    • 它不起作用,因为默认情况下列是浮动的(我忘了考虑)。如果将float: none; 添加到.proj,它应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 2022-07-19
    • 2019-06-12
    • 2020-09-11
    • 2020-11-29
    • 2014-05-16
    相关资源
    最近更新 更多