

Why the Bootstrap 3 Grid Works (2013) - analogj
http://www.helloerik.com/the-subtle-magic-behind-why-the-bootstrap-3-grid-works

======
weavie
Its worth pointing out that this all works because of the rule:

* { box-sizing: border-box; }

This rule enables you to set a % width of a column and specify a padding in
pixels without pushing the width of the columns beyond the 100%.

(I spent ages trying to replicate the bootstrap grid system and just couldn't
get it to work until I discovered this rule!)

------
csswizardry
I came up with this (in relation to Bootstrap) in 2011:
[http://csswizardry.com/2011/08/building-better-grid-
systems/](http://csswizardry.com/2011/08/building-better-grid-systems/)

This then became the basis for CSS Wizardry Grids:
[http://csswizardry.com/2013/02/introducing-csswizardry-
grids...](http://csswizardry.com/2013/02/introducing-csswizardry-grids/)

~~~
Kiro
Sorry, but the need to put "<!-- -->" everywhere is a dealbreaker for me.

Example:

    
    
      <div class="grid__item  lap--one-half  desk--two-thirds">
          ...
      </div><!--
    
      --><div class="grid__item  lap--one-half  desk--one-third">
          ...
      </div>
    

What's the rationale for using inline-block instead of float?

~~~
csswizardry
You can actually enable a CSS-only hack[1] to avoid using the comments.

Using `display: inline-block;` allows you to manipulate grids with text-level
properties (e.g. `text-align: center;` to cause grid items to fill out from
the center of the row), and also allows you to use `vertical-align:
[top|middle|bottom];` to cause columns to start from different, well,
alignments.

[1] [https://github.com/csswizardry/csswizardry-
grids/blob/master...](https://github.com/csswizardry/csswizardry-
grids/blob/master/csswizardry-grids.scss#L103-L115)

------
Zaheer
Wow - I wish I read this a year ago. Would've saved hours of frustration. My
#1 gotcha was the issue where the page would allow horizontal scrolling with
nothing on the sides. Turns out it was just because I hadn't properly added
containers/rows.

~~~
lloeki
This _will_ save us quite some time as our migration to Bootstrap 3 is long
overdue and I'm sick of span6 this and row-fluid that. Also, [0].

[0]: [https://www.ostraining.com/blog/coding/bootstrap-right-
way/](https://www.ostraining.com/blog/coding/bootstrap-right-way/)

------
eflowers
I'm the author of this blog post. If you want to talk more or ask specific
questions on problems you have or how to do certain things with the Less or
grid, post it here or on the disqus comments on the article and I'll answer
every question I get.

~~~
derengel
Is it a big undertake to read all of bootstrap to understand how it does
everything? should I read the css or less files? having only finished reading
a book about HTML and CSS.

~~~
epidemian
I'm not the author, but if you want to learn how something specific about
Bootstrap works, i'd recommend inspecting a page with the browser's dev tools.
You can immediately see which styles apply to each element, its paddings and
margins, and play with the classes' style values and see how they affect its
positioning: [http://imgur.com/ZzkF0Jb.png](http://imgur.com/ZzkF0Jb.png)

This approach has helped me a lot in understanding how many of Bootstrap
components work, and why they are structured the way they are :)

------
CmonDev
Best description of the messy state of HTML: hacking a flowing document markup
language to implement GUI. Why couldn't we just get all the nice XAML/WPF
containers in HTML5? Instead we get one more way of delivering streaming
video. Most developers have to deal with layouts - let's focus on fixing that
instead.

~~~
dasil003
Kids these days, no idea how rough we had it back when IE had 90% marketshare
and didn't update for decades on end.

You think HTML5 is just about streaming video? The standards are out there and
they are improving rapidly, look into flexbox.

~~~
visarga
Flexbox is not ready for use in projects that need to work with the browsers
people use today.

~~~
dasil003
First of all, I'll repeat "kids these days" get-off-my-lawn speech because
adoption is 100x faster than it was 10 years ago. Second of all, the point is
that the standards are addressing these issues which the original commenter
suggested they were not doing. Ignoring what standards bodies are actually
doing before suggesting they're not doing anything and proposing some random
lateral move that one happens to be familiar with is not constructive
discourse.

~~~
innguest
We've seen what W3C has put out so far (XML, XSLT, XHTML...) and they do seem
out of touch with the needs of developers.

All I'm hearing from you is "the gods will help us" when it would be better if
W3C were smart enough to specify a sane bytecode and then let innovation run
its course on top of that, instead of trying to predict our needs (which
they've shown time and again they're bad at).

~~~
dasil003
Stunning, just stunning. Not only do you put words in my mouth, but you also
fail to acknowledge anything that's happened in the last decade of web
standards (ever heard of WHATWG and HTML5?). And none of the willful ignorance
you are so deftly displaying is even germane to my point. This is one of the
worst replies I've received on HN, truly horribly conceived and executed.

------
kayman
I have unknowingly used container inside container before and it has acted
funky. Now i understand why. I also wondered why not just stuff a row and col
class into the same div tag instead of nesting div tags. This article clears
it up.

I wanted to explore foundation and uikit but always keep coming back to
Bootstrap. It has proven an invaluable item in my toolbox. Its nice to
understand the underlying reasons.

------
analogj
Incredibly well written post about why the Bootstrap 3 grid works, without
getting stuck in the technical details of how it works.

------
sergiotapia
Bootstrap's grid really is nice. I really prefer Bootstraps grid over
something like Bourboun's Neat grid system[0] where I have to pollute my CSS
with include statements.

I've also been looking into [http://purecss.io/](http://purecss.io/) since
it's grid is similar but the CSS package is lighter.

[0] - [http://neat.bourbon.io/](http://neat.bourbon.io/)

~~~
dictum
> I really prefer Bootstraps grid over something like Bourboun's Neat grid
> system[0] where I have to pollute my CSS with include statements.

What about creating silent classes for the column sizes you use and
`@extend`ing those classes?

    
    
      %three-columns {
        @include span-columns(3);
      }
      
      .sidebar {
        @extend %three-columns;
      }
      
      .menu {
        @extend %three-columns;
        background-color: #facade;
      }

~~~
scarecrowbob
This is a good idea and one I have done a bit-- IMO, it is the best of both
worlds, though I hadn't thought of using a silent class (did not know there
were silent classes, in fact).

Personally, if I am working quickly, I like having what amounts to a grid api
exposed to my html and use it a lot, but I agree that it is better if it
doesn't have to be baked into the markup.

~~~
greg5green
They are called placeholder selectors if you are looking for them in the Sass
documentation.

------
jimmcslim
As neat as the Bootstrap grid is, the day that we have broad browser support
for the CSS Grid spec cannot come soon enough.

~~~
greg5green
Even enough support to use flexbox on a daily basis would be great

~~~
acdha
I think we're rapidly there: core support is around 80% or so now, which is
definitely in the range where using a polyfill for the remaining IE 9- users
is plausible for many sites.

It'll be nice when you can assume full support but I'll take vertical
centering, easily consistent heights across elements, etc. now.

------
philliphaydon
Personally I don't like how it works. The padding / margin stuff just makes
things too difficult to work with.

/personal opinion

~~~
eflowers
What I've found is that as you try to make a grid that is robust and works for
a huge middle-ground of use cases, it really is tough. Bootstrap has a lot of
strange nuance, but a lot of the time it's "one of the only ways" to make it
work "almost every time" with CSS and HTML shortcomings and browser oddnesses.

There are smaller grids, simpler grids, etc, but none are as robust and
generalized as Bootstrap/Foundation. These have to be as close to "one size
fits all" as they can.

------
Kiro
Is the Bootstrap 3 grid better than the one from PureCSS? I'm building a thing
where I use PureCSS only for the grid so I'm wondering if I should replace it
with Bootstrap.

~~~
owenversteeg
The Bootstrap 3 grid comes with a lot of what I like to call 'premade classes'
\- like .col-md-1 or .col-xs-1 . These are used to control the grid alignment
at different sizes. Some people like them, some hate them.

I personally dislike them because CSS classes should specify what an element
is rather than what it will look like. e.x. if HN were to change from tables
to CSS they would use .topbar { background: #ff6600; } instead of .orange {
background: #ff6600; } That said, I made a CSS framework [0] that does things
differently so I am somewhat biased.

[0] [https://github.com/owenversteeg/min](https://github.com/owenversteeg/min)

~~~
mikewhy
So you use the Sass or LESS versions of bootstrap and use '@extend'

------
scotchio
This is a great post. It's worth noting though that they added .container-
fluid back into Bootstrap 3 after this post was created. Here's a quick
example of how that works:
[http://codepen.io/ncerminara/pen/omChv](http://codepen.io/ncerminara/pen/omChv)

~~~
eflowers
Thanks for pointing that out. I will go back and add that in.

------
peaton
The biggest problem I've had with bootstrap is that it is so large. There is
so much overhead. My company is working on a project and it would have taken a
ton of work to port to bootstrap.

For lightweight grids that support dynamically sized containers, masonry was
great. But there a ton of issues with keeping the content centered when the
container changes size.

We dealt with this by using inline-blocked elements with tex-align: center,
then appending invisible elements to maintain an apparent left-oriented grid:
[https://github.com/hangify/Central](https://github.com/hangify/Central)

~~~
owenversteeg
Min is an extremely small CSS framework (995 bytes) that has compatibility
with Bootstrap but unlike Bootstrap isn't prescriptive in how you do things.
It's easy to port sites to Min, and when you do the loading times will shock
you.
[https://github.com/owenversteeg/min](https://github.com/owenversteeg/min)
(Disclosure: I'm the author)

~~~
mcallan83
Min looks like a nice attempt at a lightweight framework, but it is so minimal
that I am not sure I could ever find a use case for it. One could easily start
with something like normalize and get something up and running just as quickly
as implementing Min. I like Bootstrap because I can rapidly lay out an entire
application interface in minutes. From there, I can digg into the LESS to
customize components and remove the stuff I don't need. Sure, you end up with
a larger CSS file, but if optimized it isn't much of an issue.

~~~
owenversteeg
Well, Min 2.0 will be out soon (a few days) and will include everything that
Bootstrap does and more. I guarantee that laying something out using only
Normalize will be harder than using just Min. For one, Min is about the same
size as Normalize and it supports more browsers (IE5.5+). It also provides
buttons, a grid, a navbar, etc.

Try replicating Min's navbar quickly (the v2.0 one) and you will end up with
tons of compatibility problems, strange bugs, and you'll give up quickly.
There's a reason there are only five CSS frameworks (Bootstrap, Foundation,
uikit, Ionic, Min) that actually have a working navbar. That's out of about
100 CSS frameworks total. All of those five frameworks, except Min, have a
company, thousands of stars, and tons of contributors behind them.

I don't count Gumby as its navbar has some weird bugs, plus it uses display:
table. I don't count Cascade and Ink as neither work consistently on Android.

For a preview of Min 2.0, try
[http://pasteht.ml/Rg0B0](http://pasteht.ml/Rg0B0)

------
webbrahmin
Excellent tutorial on the fundamentals of bootstrap 3. I wish I had read this
earlier. Get bootstrap should also explain the basics in greater details so
that new programmers can avoid making mistakes.

------
junto
What is the preferred method for a row that needs to span the entire width of
the container? As in, without the 15px margin on the column? Just set the
margins to 0px?

~~~
Zaheer
Can't you just not use a column? or not use a container at all? I think the
second would be preferred way according to his post.

~~~
junto
Isn't he saying that you should always use a container?

~~~
dpearce
Any content should always be in a container. The 15px margin keeps the content
from laying against the side of the browser. If you want to do a fullscreen
background or image or something then you don't need the container.

~~~
zecho
Exactly this. If you want to create a bleed, don't use a container, but if you
want content inside that bleeding element, put a container inside of it, which
will keep content from bleeding.

If you need multiple bleeds on a page, use multiple containers. Just don't
nest containers inside of containers.

~~~
eflowers
For bleeds I just use the same container structure inside of a wrapper div
that has the bleed.

For images that you want to touch the side or whatever, there is some of that
fiddling with the margins on the interior elements, yeah.

------
aagd
My problem with the Bootstrap grid is the strange choice of breakpoints,
especially on the smaller screensize end. It's way too complicated to alter
the given breakpoints or add custom ones with Bootstrap. I'd rather use
something like Susy for grids. Not so much more effort to set up, but much
less limitations. Are you really all ok with Bootstrap's breakpoints?

~~~
grrowl
IMO the smallest (fluid) size kicks in too early, but it's not hard to
customise it. You can download a customised build[1], or override the LESS[2]
or SASS[3] variables and build it yourself or incorporate it into your asset
pipeline.

Personally, I use the SASS build, include only the most basic parts
(scaffolding, type, grid, ...), customise the hell out of the variables, and
you'd never know it was bootstrap. For reference,
[http://www.recruiteasy.com.au](http://www.recruiteasy.com.au) is a bootstrap-
based site, using standard breakpoints.

[1] [http://getbootstrap.com/customize/](http://getbootstrap.com/customize/)

[2] [https://github.com/twbs/bootstrap/](https://github.com/twbs/bootstrap/)

[3] [https://github.com/twbs/bootstrap-
sass/](https://github.com/twbs/bootstrap-sass/)

~~~
aagd
I used the SASS version, too. But I found that in the end all the
customization took me more time, than I usually need to set up the site
without Bootstrap. For me Bootstrap is now more a helpful guideline than a
practical codebase.

------
ivanhoe
Nice and helpful diagrams, although IMHO explanation would be much clearer if
he used the common CSS terminology, like floats instead of things like
"positioned left/right". If I haven't already know how pull-* classes work
internally I'm not sure if I'd able to follow through.

~~~
eflowers
Some of it is with the actual "left: 20px" or whatever, using the position
rule.

------
xrjn
I've been developing stuff based on Bootstrap lately, and it amazes me how
this article appears on the first page of many of my related searches -
something like a third I would say. I don't know if this is due to the
article's excellent content or due to some good referencing.

~~~
chatmasta
I've seen his blog before too. He has a lot of really good articles with
clear, concise, and extremely useful writing.

Most of his posts get lots of thoughtful comments, and presumably high powered
links. I would assume this level of engagement+backlinking helps quite a bit
with his search ranking.

~~~
eflowers
Thanks.

I wrote the explanation above. Just good content on a topic that gets a ton of
searches, but a lot of people don't write about it in clean, understandable
ways. At the time, the Bootstrap doc didn't explain it in the same amount of
detail. Now that google recognizes the content and the backlinks and social
proof via HN, Twitter, etc, it's just on a snowball. It's at about 50k
visitors a month, mostly from Stack Exchange and Google organic searches.

Once a blog gets a few top 3 ( and a few #1) hits in a google search, it just
snowballs. I consistently get more and more visitors each day, more retweets,
etc etc. Like after today, my average visitor count will jump up and then
stabilize at a much higher average than yesterday, since once content like
this that is instructional makes waves, people just link it and tweet it
exponentially and it never dies off. Really crazy how useful content and
targeted organic SEO can work.

------
SimeVidas
What if you wanted the gutter between columns to be the same width as the
padding to the edge of the screen? E.g. in the "Columns" screenshot, gutter =
30px, but screen edge padding = 15px. How would I achieve the same value for
both? (I'm not a Bootstrap user.)

~~~
eflowers
This is a tough one. I will have to think about it, I'll try and respond here
later.

~~~
epidemian
I'm probably missing something, but wouldn't applying a 30px left and right
margin to the specific container work? E.g.:
[http://jsfiddle.net/xyM48/](http://jsfiddle.net/xyM48/)

The -15px margin on the rows and 15px margin on the columns would still do
their job, only that the rows would be 15 pixels smaller.

------
YungLean
Had to stop reading after you literally used the phrase 'this one weird
trick'.

~~~
eflowers
It was a joke. You probably knew that though.

------
vlunkr
I've always wondered why they did the padding, negative margin, then padding
system. Nice simple explanation. This is also a good resource if you want your
own simple grid system without using bootstrap.

------
armandososa
I've switched to foundation for my last projects. I just like the grid and
defaults better. Also, there's an option to have collapsed (with no padding)
columns which I've find useful.

~~~
angersock
Their block grid is pretty awesome.

The big problem comes when your project is big enough that you stop relying on
the default CSS, and need to switch over to a full SASS pipeline incorporating
their stuff. Lot to do.

------
lukasm
What to do if you need columns' sizes to be e.g. 7.5 and 4.5 ?

~~~
RayLau135
You can customise your own version of bootstrap to have double the amount of
columns, 24 instead of 12

[http://getbootstrap.com/customize/](http://getbootstrap.com/customize/)

------
chenster
What did he use to create the wireframe images?

~~~
eflowers
Just simple Illustrator boxes with a cheesy "brush" stroke effect.

------
spikyobjects
I can't help but feel bad for people who worry about this kind of thing.

~~~
hiphopyo
Indeed. I mean I love grids, but only as a tool in architecture and design.
Why some people see the need to transfer them programatically onto their CSS
---when regular CSS with media queries will do just fine---is beyond me.

