如何在不拧紧网格的情况下为Bootstrap 3的容器添加填充?

时间:2014-05-23 15:50:40

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

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

这是一个常见问题,在stackoverflow和其他地方为Bootstrap 2提供了几个解决方案,但我找不到任何对Bootstrap 3有用的东西。

1 个答案:

答案 0 :(得分:3)

其中一个Bootstrap 2解决方案涉及使用.container-fluid,它将内部网格从像素切换到基于百分比。然后,可以将填充应用于.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;
}