【问题标题】:How does one add padding to Bootstrap 3's container without screwing up the grid?如何在不破坏网格的情况下为 Bootstrap 3 的容器添加填充?
【发布时间】:2014-07-13 01:40:45
【问题描述】:

许多网站设计都需要深色背景和包含网站内容的浅色前景页面。使用 Bootstrap 时,将浅色应用于 .container div 并完成它似乎是合乎逻辑的。但是,Bootstrap 的容器在其边缘和其中的列之间没有提供任何填充,因此该解决方案提供了浅色背景,但列内容与边缘齐平 - 不好看。

这是一个常见问题,在 stackoverflow 和其他地方有多种解决方案可用于 Bootstrap 2,但我找不到任何对 Bootstrap 3 有用的解决方案。

【问题讨论】:

    标签: css twitter-bootstrap background twitter-bootstrap-3 padding


    【解决方案1】:

    涉及使用 .container-fluid 的 Bootstrap 2 解决方案之一,它将内部网格从像素切换到基于百分比。然后可以将填充应用于 .container-fluid 中的背景 div,内部列将无缝调整以适应。这似乎是一个不错的方法,但用于调整其他一些样式的特定 CSS 不适用于 Bootstrap 3。

    在挖掘 Bootstrap 源代码后,我注意到 grid.less 中 .container 和 .container-fluid 规则之间的唯一区别是三个媒体查询。我将页面内容包装在 .container-fluid 中,然后用包含媒体查询的内容覆盖其定义,以便页面内容的响应与使用标准 .container 的页眉和页脚相同。

    这是 HTML:

    <html>
    <head>
      <title>Bootstrap 3 Container Padding Example</title>
    </head>
    <body>
      <div class="page-container">
        <div class="container-fluid">
          <div class="page-bg">
             <!-- PAGE CONTENT -->
          </div>
        </div>
      </div>
    </body>
    </html>
    

    然后是 .less:

    .page-container > .container-fluid:first-child {
      .container-fixed();
    
      @media (min-width: @screen-sm-min) {
        width: @container-sm;
      }
      @media (min-width: @screen-md-min) {
        width: @container-md;
      }
      @media (min-width: @screen-lg-min) {
        width: @container-lg;
      }
    }
    

    然后在 .page-container div 中添加填充:

    .page-container {
      .page-bg {
        padding: 15px;
        background-color: #EFEFEF;
      }
    }
    
    body {
      background-color: #333
    }
    

    这似乎有效。我尚未完成将驻留在此容器中的界面的样式,因此可能会出现问题,但到目前为止一切似乎都很好。

    Here is a working example of this solution on codepen.io.

    请注意,上面的解决方案在包含 Bootstrap 的变量和 mixins .less 文件后使用了 less.css。这是编译后的 CSS:

    .page-container > .container-fluid:first-child {
      margin-right: auto;
      margin-left: auto;
      padding-left: 15px;
      padding-right: 15px;
    }
    @media (min-width: 768px) {
      .page-container > .container-fluid:first-child {
        width: 750px;
      }
    }
    @media (min-width: 992px) {
      .page-container > .container-fluid:first-child {
        width: 970px;
      }
    }
    @media (min-width: 1200px) {
      .page-container > .container-fluid:first-child {
        width: 1170px;
      }
    }
    .page-container .page-bg {
      padding: 15px;
      background-color: #EFEFEF;
    }
    body {
      background-color: #333333;
    }
    

    【讨论】:

    • 为了清楚起见,.page-container div 的用途是什么?谢谢!
    • 我使用 .page-container 作为应用程序主页模板根附近的布局容器。这样,如果我想要一个具有多种水平布局类型的页面,我可以将页面容器 div 与可能扩展页面的整个宽度而不是限制媒体查询断点宽度的横幅容器 div 混合使用.无需包含此技术即可正常工作。
    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 2021-05-05
    • 2021-02-01
    • 1970-01-01
    • 2019-11-20
    • 2011-08-19
    • 2011-03-11
    • 1970-01-01
    相关资源
    最近更新 更多