Bootstrap Grid的精妙之处(译)

原文地址:The Subtle Magic Behind Why the Bootstrap 3 Grid Works

Things like CSS grids should remain behind the curtain. No one really needs to know how it works, or why. Until you have a broken design or something complex and you can’t figure out why your spacing, margins, paddings etc are all messed up. It can be a real pain, especially when you are generating content dynamically in some sort of interface that changes and shifts.

12bet,一直感觉像 CSS 栅格系统之类的东西拿过来用就好了,不用深究背后的原理。12bet,直到有一天你发现简单的套用在稍复杂的页面上出现问题,间隔啊,12博体育,内外边距啊,哪都不对劲儿。

Container

Container有两个作用:

  1. 12博体育,在随时可能的宽度变化(响应式)中提供宽度限制。当页面宽度变化,container 的宽度也随之变化。12bet,并且其中的 column 的宽度是基于百分比,所以他们的值不需要变化。
  2. 提供一个水平方向的 padding,使其内部的内容不会接触到浏览器的边界,大小为15px,就是图片中粉红色的部分,12bet,作用会在下面说。

注意,不需要也不应该在 container 中嵌套另一个 container。

Row

Row 是 column 直接存在的容器,按照文档描述 row 中最多可有12个 column,不过可以通过 nesting 的方式灵活扩展。同时作为都是左浮动的 column 的 wrapper,自带 clearfix 的性质。

同时 row 还有一个很特殊的地方,就是左右各有 -15px 的 margin,就是图片中的蓝色部分。这样也就抵消了上面提到的 container 中15px的 padding,那么为什么要这么折腾呢?接着看往下读。

注意:千万记住要把 row 放到 container 的内部,这样才能保证正常。

Column

注意啦,每个column 也会有15px的水平方向的 padding,也就是图片中黄色的部分,唉,先别急,会明白的。还记得上面提到的 row 的作用吗,colunmn 只能在 row 中生存,由于 row 的 margin 为-15px,那么位于两边的 column 就碰到了 container 的边界。但是 colunmn 本身又有 15px 的 padding 使得它其中的内容并不会碰到 container,同时 不同column的内容之间就有了30px的槽。结合图片看一下就一目了然了。

注意:一定要把 column 放到 row 里使用。

Nesting

当把上面一系列的 container, row, column 都设置好,就可以通过 nesting 扩展它栅格系统了,也就是在 column 中直接嵌套 row,而不需要再套一层 container:

还记得 container 和 column 都有15px的 padding 吗,对在 nseting 的时候 column 的作用也相当于 container 了,这样就可以实现任意的嵌套了。

这正是 Bootstrap 栅格系统的最巧妙的地方!

Offsets

Offset 就很普通也很简单了,仅仅是通过增加 left-margin 实现。不过有点奇怪的是,如果是紧挨着 row 内部的 offset-column 的 offset 是从 row 的-15px的 margin 算起的,而相对于另一个 column 的 offset-column 却是从那个 column 的外边界开始偏移,不过不要纠结这些,这真的不重要(其实这也不奇怪,就是从 column 的做左界开始偏移)!这样就导致了两个 column 之间的槽被 offset 分隔开。除此之外,和正常的 column 表现完全一样。

Push and Pull

Let me start by saying why you push/pull: to flip layouts based on responsive sizes. Especially good for reordering how columns are laid out from a mobile design, to the desktop design, as it allows you to break the HTML top -> left drawing of divs.

首先来说下为什么需要 push/pull:直接地说就是可以改变 column 在 HTML 中的顺序。

不过有一些搞不清楚的是 push/pull 是通过 positon 实现的。Push 是通过加 left,例如.col-md-push-3 { left: 25%; }。Pull 是通过加 right 实现。由于 column 是相对定位的,可能会和其他 column 发生重叠。

使用时需要注意,不像 offset 那么直接,一般用了 push/pull 配合着一起用,要注意重叠的问题。

Author image
关于 superlin
Beijing, CN 主页
The reason why a great man is great is that he resolves to be a great man.
 
 
默认颜色 边栏居左 边栏居右