CSS: Order Matters!

Twitter’s Bootstrap platform offers what’s known as “responsive layout.” This means that by including one extra CSS file, the elements on the page will be positioned and aligned depending on the resolution of the client’s screen. This essentially gets you an automatic mobile site with no extra work.

Almost.

I was having an issue with a project where there was a large bit of whitespace above the navigation bar. I thought I was following the docs exactly, and I couldn’t figure out what the issue was. Turns out that the position of one line of code in the source was the root of my problem.

This was my code, with that mysterious white pad atop the navbar:

<link rel="stylesheet" href="bootstrap/css/bootstrap.css" />
<link rel="stylesheet" href="bootstrap/css/bootstrap-responsive.css" />
<style>
	body { padding-top: 60px; }
</style>

And here’s the code that works as intended, with no padding:

<link rel="stylesheet" href="bootstrap/css/bootstrap.css" />
<style>
	body { padding-top: 60px; }
</style>
<link rel="stylesheet" href="bootstrap/css/bootstrap-responsive.css" />

See the difference? That 60px of padding is required to prevent the page contents from being hidden underneath the navigation bar. When bootstrap-responsive.css is included before the padding is defined, the mobile view will be rendered with the padding applying to the navbar. When it is included after the padding is defined, it apparently overrides the padding and the page is displayed as intended on mobile devices. I haven’t taken the time to go through the CSS to figure out what is responsible for this, but if I do I’ll update this post.

So, the next time your page isn’t rendering the way you want it, and everything looks like it’s perfect, try moving things around. You never know when that one-off override is sitting in an import file, messing with your otherwise-perfect layout…

2 Comments

  1. Did the exact same thing, could not figure out where on earth this mysterious padding was coming from when window size < 900px;

    Bumping inline style above responsive.css include did the trick.

    Thanks!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>