Beating Borders: The Bane of Responsive Layout

by on 18th January 2012 with 45 Comments

screenshot

Responsive design often requires setting your widths using percentages. This is easy enough to accomplish, that is until you start throwing borders into the mix. If your columns and total width are set using percentages, a static border size wreaks havoc on your layout.

Today we’re going to look at a couple of different ways to beat this problem. You’ll learn how to create a completely fluid layout that doesn’t mind extra borders or padding one bit.

Responsive Design Is Easy… In Theory

Responsive design is currently our best answer for serving up optimized content to the wealth of different devices and screen sizes that access the web today. With a few basic media queries we can quickly and easily take a static design and turn it into something that evolves based on the user’s unique needs. How amazing is that?

“Real world coding has a way of surprising you”

In theory, this looks nice and simple to me. I’ve spent a lot of time both reading and writing about responsive design, so I know both the theory and the practices well enough that I should never encounter any major hurdles. However, real world coding has a way of surprising you. No matter how prepared you think you are, when it comes time to actually bring your project to life, some major hurdles are bound to present themselves. Especially when you’re approaching complex layouts in CSS.

There are a million issues that arise in situations like this but today I want to focus on one that specifically threw me a curve ball: borders. When designing responsive layouts these seemingly innocent touches can have the effect of ruining everything!

Responsive Math

When coding a full on responsive site, one highly recommended practice is to use percentage based widths on your content. Sure, you can combine media queries with static widths, but then your layout isn’t nearly as adaptive as it could be. If that’s the ultimate goal, why not go all the way?

Combining multiple column layouts with percentage based widths involves a little bit of math, but it’s actually super basic and can be handled by anyone with basic addition and multiplication skills (we performed this next bit in our responsive thumbnail gallery tutorial).

Let’s say we want a five column layout. The first thing I like to do is think about margins. If we want 4% margins between our columns, 4% times 5 columns equals 20% of our width being reserved for margins. Then we subtract 20% from the total width (100%) to come up with 80% left for the actual columns. 80% divided by five columns equals a 16% width on each column. Here’s a graphic to make everything a little clearer:

screenshot

Putting this math to good use in our CSS would look something like the following. Pretty easy right?

.column {
	width: 16%;
	margin: 0 2% 0 2%;  /*2% right +2% left = 4% margin*/
}

The Border Problem

Not so fast. Let’s say we want to add a border to our design. How do we do that? Normally we would simply add a border to the column class, but we’ve already accounted for 100% of the width in the layout above. Adding border completely screws up our layout. Here we have five columns distributed via the CSS above:

screenshot

And here’s what happens when we add a border of say, 2px to a column:

screenshot

The solution of course would be to account for the border in our previous math, but how do we go about this? It turns out, we can’t set the border size as a percent, only a static value. This is problematic because if we use percents for everything else, the amount of space that we leave for the border will be a varying value, meaning it will change as the page width changes. This makes it nigh upon impossible to decide on a width for our borders! So what do we do? Should we give up and scrap the border idea?

CSS Outline to The Rescue

Obviously, what we need is a way to apply a border to a column without screwing with its width. As any good CSS trickster knows, there is in fact a property that does just that: outline. Using the following code, we can leave our math exactly as we figured before and still come away a border-like effect that doesn’t break our layout.

.column {
	width: 16%;
	float: left;
	margin: 0 2% 0 2%;
	background: #03a8d2;
	outline: 2px solid black;
}

This works great for our test, the columns flow nicely and fit perfectly in the space provided despite the outline:

screenshot

Headaches

We found our solution, let’s pat ourselves on the back and call it a day! Unfortunately, there’s always a caveat. In this case, there are several.

Browser Compatibility
The first issue that arises with using the CSS outline property is of course browser compatibility. To be fair, the situation here could be worse. We’ve got great support across the board in modern browsers: Safari, Chrome, Opera, even IE! Unfortunately, IE support only goes back to IE8 with IE6 and 7 having zero support.

Many developers have only recently decided that they can scrap IE6 support so I know many won’t be willing to do the same for IE7 just yet. However, the good news is that this is purely a subtle aesthetic touch and it’s definitely not going to ruin my day if everyone sees the outline except IE7 users.

Firefox Box-Shadow Problem
Even though Firefox fully supports the CSS outline property, you have to be really careful how you use it. Specifically, you’ll run into problems if you combine an outline with a box-shadow. To see what I mean by this, here’s an outline and a box-shadow rendered in Safari (the good way):

screenshot

Now here’s the exact same code rendered in Firefox (the messed up way):

screenshot

As you can see, for some crazy reason, Firefox places the outline outside of the shadow rather than on the true edge of our column. This results in unacceptable ugliness!

All Or Nothing
One final thing to remember about CSS outlines: you can’t apply them selectively. With borders, you can use border-right, border-top, etc. but with an outline you’re forced to accept the idea that it will be uniform all the way around the edge of your object.

Another Solution: box-sizing

The CSS outline has a lot of baggage! It solves our problem but comes with a pretty hefty set of instructions that you might not care for. If only there a way to use the far superior border property but adjust the CSS box model to our own devices. Well you’re in luck, because there is in fact just such a property: box-sizing.

This magical property allows us to tweak that ever confusing box model. The default value of box sizing is “content-box”, which is essentially the box model that we know and love. The width and height values determine the size of the content and any padding or borders are drawn outside of that and therefore add to the width. So a 200px wide div with a 2px border technically eats up 204px of space.

border-box

The other possible value for box-sizing is “border-box”, which actually places any padding and borders inside of the specified height and width. This means that a 200px wide div with a 2px border is still only 200px! Here’s what this looks like if we apply it to our columns:

.column {
	width: 16%;
	float: left;
	margin: 0 2% 0 2%;
	background: #03a8d2;
	border: 2px solid black;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	box-sizing: border-box;
}

With this code, our columns are flowing perfectly despite having borders applied:

screenshot

We can even take this a step further and add some padding to the equation without screwing anything up. As long as you have the box-sizing property set to border-box, no additional math is necessary. Add all of the borders and padding that you like and everything still works:

.column {
	width: 16%;
	float: left;
	margin: 0 2% 0 2%;
	background: #03a8d2;
	border: 2px solid black;
	padding: 15px;
	font-size: 13px;
	-webkit-box-sizing: border-box;
	-moz-box-sizing: border-box;
	box-sizing: border-box;
}

screenshot

Browser Compatibility

Interestingly enough, browser compatibility here is the same as with outline, meaning this works on pretty much everything but IE6 and IE7. Your main concern here though is that, unlike with outline, the layout will in fact fail in browsers that don’t support this property.

Which Method Is Best?

The outline property is definitely the simpler fix, it works in a lot of situations and if it fails, nothing bad happens to your layout. However, I think that the box-sizing method just feels so much better. I can combine it with a shadow without any serious problems, browser support is actually not bad and I can still enjoy all the goodness of borders. The fact that padding can also be thrown into the mix is icing on the cake and brings this way ahead of the competition in my mind. If you’re worried about IE7, you can always whip up a quick conditional stylesheet that solves the problem.

Demo

If you want to see box-sizing in action, cruise over to Dabblet to see the live demo of the example above.

screenshot

Conclusion

Outline and box-sizing represent two possible solutions to our problem of combining borders with percent based widths in CSS layouts. Neither solution is perfect, but as long as you know what you’re doing, both can be used to successfully solve your layout woes.

Now that you’ve seen my solutions for this problem, it’s time for you to chime in. How do you handle the problem of borders in responsive layouts? Do you have a different solution not listed above?

Comments & Discussion

45 Comments

  • GhostInTheAndroidMachine

    Rather than struggle with making query-responsive / rubber sites and having to ditch all the web coding practices I spent 10+ years using, just to join the herd, which will probably prove pointless in 3-5 years when responsive isn’t trendy anymore or phones have changed, I have an easier solution to all of these headaches: Just make the site like you used to, and then make a mobile sibling site. You know, like almost all of the major Alexa sites do. Mobile sites have a mobile context. The user experience and attitude is different when mobile. Info architecture and layouts have to be mobile, not “responsive enough to work on a small screen.” A sibling mobile site, imo, is a better solution anyway. As for cost and time, I don’t see how it would take longer than trying to design a site that can rubberize on 20 screens, show/hide stuff depending on about 50 factors, transitions, scaling, doing s bunch of math to account for borders (reminds me of all the floating battles and float clearing bull), etc.

    • http://legacycreativestudio.com MikeLegacy

      The problem with separate mobile sites in comparison to responsive design is that developers don’t redirect sites correctly. I can’t even count how many times I’ve went to MAJOR news publication sites, and clicked on a Google News article and was redirected to the mobile version, where that page exists, but at a different URL, so I was just taken the the mobile homepage instead.

      This is horrible UX practice, and why having one code base will always be the better solution.

      Just because you don’t want to throw away 10+ years of experience and learn something new doesn’t mean this new way isn’t better.

      Do you apply this logic to everything in your life?

      Responsive is the future, and you are seeing a large portion of the web take responsive design under their wing, and it’s a great thing to see.

      The best thing about responsive design is that it is future proof, No matter what screen width/size is, responsive layouts ADAPT.

      If you are spending a longer amount of time making your site responsive that you would creating a WHOLE SEPARATE SITE, then you either don’t know what you are doing, or whatever designers you are working with don’t understand the limitations of responsive design and are giving you over complicated designs.

      You are right about one thing, mobile SHOULD be a different experience from the computer, and responsive restricts design in a GOOD way. It limits you to only displaying information that is most important to a user, and starting with the mobile version in a responsive site should be a part of any digital designer’s strategy.

    • Dillon

      What, can’t adapt to change after ten years in the business? People who are against responsive design either can’t do it, or are just ill-informed. It’s not a trend.. It’s the most efficient way to build a website possible. Your mobile sibling sites aren’t going to work on every device. And what are you going to do, create more sibling sites for more mobile devices as they come? Right. You can keep doing that, and I’ll be here waiting to take your job.

      I’d elaborate on the merits of responsive design here, but there are far too many articles out there that would explain it more thoroughly. I suggest reading them.

      If anything, I believe the future will entail some sort of fusion of current web practices.

  • http://www.inserthtml.com/ Johnny

    This is very useful! I always run into this problem, I didn’t even think of the border-box solution.

  • http://semanticbloom.com Yuri P.

    Good overview. But actually where’s beating of the bane (ie IE<9)?

  • http://bohemianalps.com Jason Simanek

    For more old-browser support, you could use your percentage-widths for column elements and then use a div or something inside each column element with

    display:block;
    overflow:hidden;
    border:solid 1px #000;

    That gives you broad browser support and greater control over the border properties. One drawback: a little bit additional markup that doesn’t have any semantic value.

  • Joshua Johnson

    Interesting solution Jason, thanks for offering it up!

  • http://www.stevendsanders.com/ Steven D. Sanders

    @GhostInTheAndroidMachine-

    One of the goals of responsive design is to support not only mobile devices, but ALL devices. Let’s say that you are designing a site with a fixed width of 1140px and a separate mobile site. Now anyone with an iPad is going to get your mobile site, which is not ideal at all for an iPad. So, you switch to a width of 960px. Now, anyone with an increasingly popular high resolution monitor is going to have huge margins on both sides of your site.

    You are right that responsive design will probably be gone in 3-5 years. Someone will come up with something better that will fit the web landscape at the time. Right now, the amount of different resolutions that people use on the web is getting extremely diverse. Responsive design is the natural solution to the problem.

  • http://twitter.com/dgeerdink Daan

    To be honest I don’t think responsive design will die or be replaced any time soon. It’s something we’re sort of being forced to do now with all the different mobile devices and screens with different resolutions and pixel ratios.

    See this article for a better insight into pixel ratios:
    http://www.alistapart.com/articles/a-pixel-identity-crisis/

    Thanks for the article. Interesting techniques and the box-sizing property is definitely the way to go here. You can indeed just serve up different styles for IE6/7 if you need to support them.

  • http://Jordandobson.com Jordan Dobson

    Also, you can consider using the ::before or ::after pseudo elements to add a border.

    Just absolutely position it on top of your content like so…

    .column::before{ content: “”; position: absolute; top: 0; bottom: 0; left: 0; right: 0; border: 2px solid black; }

    Something along those lines would also do the trick… except for IE7.

  • Mads Kaastrup

    I Think Jason’s solution is the best workaround.

  • Joshua Johnson

    Another great solution Jordan. Thanks for the tip.

  • Dels

    Surely i’ve read elsewhere in the web that IE6 way to layout margin & padding is actually somewhat like applying “border-sizing:border-box” so the margin & padding are in width scope (one of most popular bug)

  • Dels
  • http://stacklayout.com camslice

    just add an internal wrapper element inside your percentage width elements. then apply anything you want to that: padding, margins, borders, shadows, whatever.

    100% cross browser. nuff said.

    did i hear you say ‘extraneous’?… sure, but most wrapper-type elements are not extraneous. in the real world, more elements = more hooks for styling and programming. just take a look at the source of facebook (as an extreme example).

    i’m all for clean, minimal and semantic markup, but why resort to ridiculous CSS techniques that are not cross browser compatible when a few wrapper divs can not only solve this problem, but open up even more options?

    and go

  • http://www.inpixelitrust.fr Stéphanie

    Wow, I knew about box-sizing but not outline, shame on me really. Thanks for the discovery.
    Jordan Dobson’s pseudo-class is also an interresting solution.
    I would also agree with serving a different stylesheet for IE to “fix” the non compatibility, or better, using Paul Irish’s trick (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/) and using a specific class on html to target IE.

  • Boab

    My head just exploded at all the ignorance and misinformation in GhostInTheAndroidMachine’s comment :[

  • http://strom-im-zoo.de/ Pipifix

    Whats about the box-shadows spread value? Its simple to fake multiple borders without touching the box-model. I’ve used this trick in several (responsive) web projects. For a deeper insight have a look at this example: http://blog.w3conversions.com/2011/09/css3-spread-value-and-box-shadow-on-one-side-only/#attachment_941

    Greeting from Germany.

  • http://themebit.com/ Michał

    Very useful, thank for this post Joshua.

    I new the ‘outline’ property existed, just assumed browser support was much poorer. Box sizing I never heard of, looks very promising, I’m definitely going to give it a try.

    @GhostInTheAndroidMachine – ‘responsive design’ may be a current buzz word, but the problem it tries to solve is real and I very much doubt it will disappear any time soon.

  • http://my.opera.com/fatal Andrey Petrov

    Unfortunately using an outline is not a solution in most cases since:
    “Unlike a border, adding special instructions for one side of the outline (like outline-left-width) is not possible. You can define only a complete outline around the entire element.”

  • http://mattwilcox.net Matt Wilcox

    I proposed we get % accepted as a valid unit for border-width on the www-style mailing list: http://lists.w3.org/Archives/Public/www-style/2012Jan/0084.html

    Another solution is to wrap the div you want a border on inside another div, use padding as a percentage, and give the wrapping div a background colour of what you wanted the border to be.

    There are no neat solutions, and it’s a daft problem to begin with – % should be valid.

  • Robert O’Callahan

    ‘calc’ (supported in IE9 and in Firefox as -moz-calc) would help you a lot here, once it’s supported in all browsers.

  • http://www.saelstrom.com Ulf

    @GhostInTheAndroidMachine

    – Like

  • http://lesscoffee.Be Kristof Houben

    You could also use box-shadow for the borders and give it a spread. You can use as many box-shadows as you want so if you want to add a shadow afterwards that is also possible.

    K.

  • http://lesscoffee.Be Kristof Houben

    Just noticed @Pipifix said the same thing ;)

  • http://www.johnandjohn.nl Dio Vayne

    How about making columns like this:

    x

    x

    .column {
    width: 50%;
    background-color:#333;
    float:left;
    }
    .columnContent{
    background-color:#FFF;
    display:block;
    margin:1px;
    }

    .column{24%}
    .columnContent{}

  • http://www.johnandjohn.nl Dio Vayne

    Sorry. Apparently I can’t edit or delete my post and I can’t post code.

    What I’m trying to say:

    each column has a background color of the border. Inside each column is a column-content div with a white background and a margin of 1px;

  • Pixelutely

    Box-sizing property resolves the border issue like a charm.

  • Glen

    For ie7 and likes, modernizr could be used to target browsers with no support from your CSS, or via conditional class on the HTML tag – as is in HTML5 Boilerplate.

  • http://bingojackson.com Rhys Thomas

    Outline is all well and good until you come to want rounded corners. there is no outline-radius: 5px;
    As for % widths on border I don’t understand why you would want them. You add a 2px border because it looks nice, it’s the right size. You decided it was the right size after a lot of playing around with other sizes. What you don’t want is someone taking you perfect border and resizing it to some large, ugly size that totally detracts from your text or a size so small you no longer have a border.
    Use box-sizing or whack a wrapper in and stick the border on that, or just forget that IE7 exists and code for newer stuff.

  • http://Sudhq.com Roy

    Why not add some extra markup.
    Just trow a div with let’s say class .inner in the column and style this.

    Example:

    Your content.

  • http://iamfriendly.com/ Richard Tape

    Not that I’m advocating horrible hacks, but if you absolutely must support IE7 (and in many cases why wouldn’t you?) then there’s a pretty useful polyfill for box-sizing:

    https://github.com/Schepp/box-sizing-polyfill

    I pop it into a separate ie7.css which only gets loaded for that browser and I simply copy all of the selectors which I use box-sizing for in my main stylesheet into this IE7 stylehseet and apply the .htc hack to them. Slow, cumbersome, hackish, ugly…but sometimes you gotta do what you gotta do.

  • http://www.technbuzz.com Samiullah Khan

    (Correct me if i am wrong)
    I don’t think that IE would any problem using box-sizing as a border-box;
    Because even the IE-6 by default has the ability to act as border-box rather than content box

  • http://www.howtomake.com.ua howtomake

    hello my dear!
    you can add border:

    background: #000;
    padding: 0.15%;
    width: 15.7%;

    put some info in .column div {max-width: 100%}

    maybe i right?

    ps. sory my english – low(

  • http://www.howtomake.com.ua howtomake

    and .column div {width: 100%; background: #03a8d2;}

  • Inita

    why not to make a border with box-shadow ? :/

  • http://www.squadpoint.com Chris (squadpoint.com)

    As a few people have noted, I have always used a div inside the column layout div and styled that. Bit more markup, but not much!

    Will probably give the box-sizing a go though, as it seems slightly more elegant.

  • Kevin L

    A div inside each column with the padding and border applied to it solves this problem as a poster named Jason above mentioned. That’s actually the standard way to go around the problem that publications such as A List Apart have preached for years now, but thankful for enlightening me about outline and the box-sizing method to replace such old methods in a few years.

  • David

    The div inside a div technique is a handy way of getting around the issue, however, it’s not exactly semantic and your HTML can become unnecessarily bloated.

    The box-sizing rule is exactly what I was after. And, as Joshua rightly pointed out, adding a little conditional styling to IE6 and 7 and you’re good to go.

    Also: It worries me that someone who’s been in the business for 10+ years – as GhostInTheAndroidMachine claims – cannot see the overwhelming importance of a more flexible web.

  • http://www.bharath.co.uk Amarjit Bharath

    This is why we use inner divs within divs.
    The inner div’s margin is set to simulate the parent’s padding.

    This leaves your outer div width set to what you need. You can then add a border to your inner div.

    It’s a little extra work but adding your borders to the inner div will work in all browsers.

    Amarjit.

  • Dark Phoenix

    Little secret: Although you have to be somewhat careful with it, IE6/7 in quirks mode uses the border-box box model. However, that likely will open up a new can of worms for designing websites…

  • http://www.floridatattoo.com/UserProfile/tabid/1450/userId/84379/Default.aspx 1000 andkon games andkon arcade

    Consequently if you’ve heard about Tribe Pro and
    looking to find out what it is and how it can increase your web site rankings, you’ve landed on the right
    page. I have observed that quite often, the articles you find on blogs are more voluminous than those on online magazines,
    not to talk of the short questions on forums. Knowing this we just need to
    find websites that the major search engine crawls frequently.

  • http://www.la-peaceandfreedom.org/acquireable-elderly-home-health-care-in-new-york/ Chelsey

    Hi there! I know this is somewhat off-topic however I needed to ask.
    Does operating a well-established website such as yours take a lot of work?
    I am completely new to writing a blog however I do write in my journal every day.

    I’d like to start a blog so I can share my personal experience and feelings online.

    Please let me know if you have any suggestions or tips for new aspiring bloggers.

    Appreciate it!

  • https://www.youtube.com/watch?v=HSoNAvTIeEc Youtube.Com

    Hi! This is kind oof off topic but I need some guidance from an established blog.
    Is it difficult to set up your oown blog? I’m not very techincal but I can figure things
    out pretty fast. I’m thinking about creating myy own but I’m not
    sure where to start. Do youu have any tips or suggestions?
    Thank you

  • http://www.facebook.com/permalink.php?story_fbid=685532464830056&id=685531631496806 La Planète des singes l’affrontement fr

    Reality based films also grab the attention of many.
    The rally and passing of Resolution 1010 pave the
    way for proposing House Bill 1286, which will double the incentives offered by the state to attract more film,
    TV, and media productions. With Luigi Lo Cascio, Catrinel Marlon, Luigi Maria Burruano.

    Visit my web page – La Planète des singes l’affrontement fr

Subscribe
Membership
About the Author