Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Why the Bootstrap 3 Grid Works (2013) (helloerik.com)
503 points by analogj on July 16, 2014 | hide | past | favorite | 83 comments


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!)


I came up with this (in relation to Bootstrap) in 2011: 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...


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?


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...


We're using CSS Wizardry Grids in a new project at Precision Nutrition. It's been pretty great so far, though the use of comments is quite something to wrap your head around with respect to grid items.


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.


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/


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.


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.


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

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


Read the doc and the Less files. To really use bootstrap, you gotta use their Less and then your own on top of it.


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.


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.


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


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.


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).


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.


The only HTML what is there is the "class" attribute. The rest is CSS.


And awesome data-* attributes right?


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.


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


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/ since it's grid is similar but the CSS package is lighter.

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


Funny I think a lot of people would say the opposite. That they'd rather the grid code was in their CSS than in their HTML. Makes it much easier to change layouts if your grid code is defined in the CSS itself. Plus you get to manage them per screen-size however you want. To each their own.


> 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;
  }


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.


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


If you like Pure you might like my framework Min. It's way smaller than Pure and v2 (released in a couple of days from now) will have full compatibility with Bootstrap. https://github.com/owenversteeg/min


I like Min but the 10-column grid seems like a poor choice vs 12-col, IMO. What was the rationale behind that?


It was ridiculous, but back for Min 1.0 and 1.5 I couldn't fit in the extra ten or so bytes gzipped and minified. Back then, Min's priorities were "fit in as much stuff in 995 bytes and support IE5.5 as an intellectual exercise".

They have since shifted to "make a CSS framework that can actually be used by other people, while still staying under 995 bytes". I also got another person (Scott O'Hara, https://github.com/scottaohara) to contribute; he made several useful contributions and also made size optimizations. As a result, Min 2.0 will be 995 bytes and also include a (clearly superior) 12-column grid. It will also include many other useful features, like a better responsive navbar and better icons, include all of Bootstrap's features, and it will still support IE5.5+.


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


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


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.


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

/personal opinion


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.


I've found the padding/margin issues annoying, too. But I'm only ever a few StackOverflow searches away from finding the right CSS to use to override the defaults. Also, it's helped playing around in Chrome devtools to inspect where particular CSS values are coming from. But on balance, I like Bootstrap. :-)


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.


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


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


I have no experience with PureCSS but I've found Bootstrap very dependable. If you're designing for multiple screen sizes be sure to take the time to assign multiple column sizes (col-xs, col-sm,...) to columns.


I've heard people rant and rave about Bootstrap being superior. I used it a few versions ago, so I couldn't tell you either way, so you might want to check that out too.


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


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


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


With Less, you can pare bootstrap down to just the bare minimum of what you need, all the way down to just using the grid an nothing else. When you compile your Less, it's super slim.

My focus wasn't on the bootstrap CSS customizer though, I try to recommend people use their own Less to keep things under control.


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 (Disclosure: I'm the author)


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.


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


I've been really happy with PureCSS[0], and it seems to be gaining quite a bit of traction lately (over 8000 stars on GitHub). PureCSS is very small and modular. If I didn't like PureCSS so much, I would probably roll my own grids using Bourbon Neat or Susy.

0 - http://purecss.io/


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.


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?


I would add a negative margin to the content, or create another layer of container with negative margin after .container > .row > .column


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.


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


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.


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.


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.


.col needs to be in a .row which provides clearfix, of course this is only one of the reasons.


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?


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 is a bootstrap-based site, using standard breakpoints.

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

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

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


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.


It is super easy to overwrite breakpoints in the variables, or just make your own. Especially if you use Less to define your grids and not HTML, you can just reference whatever you want, like:

@media (min-widht: @eriks-custom-width); {}

That syntax is off but you get the gist.


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.


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


Except that positioned left/right is the correct way to say it in CSS-speak.


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.


These articles get about 50k visitors a month between the 3 Bootstrap articles. It's just clean SEO optimization to make Google like it, and then good content and tons of people who backlink them and tweet them.

It's legit ground-up SEO and content success, no magic. And, it helps that no one has ever tried to write Bootstrap articles and explanations like I did in my 3 articles.

BTW I am the author if that's not obvious =D


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.


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.


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.)


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


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/

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.


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


It was a joke. You probably knew that though.


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.


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.


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.


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


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

http://getbootstrap.com/customize/


The less mixin version of making the columns can be any value as it does some math to take it to a percent. So a 6 is a 50%, so if you want a 7.5, it will just change that to a % and then your 4.5 will fit right in. You can do this with almost every Less value bootstrap looks for. Really slick.


What did he use to create the wireframe images?


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


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


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.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: