.. Your Daily Design Dosis

11 Useful CSS Code Snippets for Responsive Web Design

| 23 Comments

Mobile responsive web designs have become extremely popular in the last 2 years, and with a very good reason. As such it’s common to see more code snippets published on the blogosphere, Github repositories, Codepen docs and more.

You’ve probably heard about responsive web design these last 2 years, but in a nutshell, it all boils down to this:

A responsive website means quite literally that it responds properly to all devices and screen sizes. It is done by scaling down or re-organizing content on the page using some CSS and HTML trickery, in order to create the best possible user experience on your site.

In this article I would like to share some of the ‘life changing’ CSS code snippets I use on a daily bases, so let’s quit the BS and start hitting the road, Jack!

HTML Meta Tags for Responsive Layouts

The meta viewport tag is the only one which should be required for responsive layouts. This will set the view on all screens at a 1×1 aspect ratio. This will remove the default functionality from smartphone browsers which render websites at full-view and allow users to zoom into the layout by pinching. The other two tags are supported in Mobile IE and older smartphone browsers, but aren’t necessary for mobile effects in your layout.

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="true">

Media Queries

CSS3 supports all of the same media types as CSS 2.1, such as screenprint and handheld, but has added dozens of new media features, including max-widthdevice-widthorientation and color. One can create multiple style sheets, as well as basic layout alterations defined to fit ranges of widths — even for landscape vs. portrait orientations.

Multiple media queries can also be dropped right into a single style sheet, which is the most efficient option when used:

/* Smartphones (portrait and landscape) ----------- */
@media only screen
and (min-device-width : 320px)
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen
and (max-width : 320px) {
/* Styles */
}

Max and min width

Max-width property allows you to set the max width of the element. The purpose of max-width is to prevent the element from extending the boundary. Min-width is opposite to max-width – it sets the minimum width of an element where the element will never be smaller than the provided value (Max- and min- properties can be applies to height as well).

There will be a conflict between max-width and width properties. To ensure that the width will not override and take over write them in the order provided in the following example:

.container {
	width: 800px;
	max-width: 90%;
}

Flexible Images and Media

Another aspect of responsive Web design is flexible images and media. Scaling in CSS is pretty simple to implement for images. You can set the media element’s max-width to 100 percent, and the browser will make the image shrink and expand depending on its container. You should supply the image in the best quality and size possible and then let CSS adapt the image to the right size.

img { 
  max-width: 100%; 
  height: auto;
}

Note: max-width is not supported in IE8 and lower, but a good use of width: 100% would solve the problem neatly in an IE-specific style sheet. One more issue is that when an image is resized too small in some older browsers in Windows, the rendering isn’t as clear as it ought to be.

Getting typography to scale

Type scales nearly endlessly and reflows into any sized container we give it. Ideally, when our overall layouts scale, so should your type, and here’s a quick and simple example how to do it. We’ll look at how to make your fonts fit your layout nicely no matter what the device or screen width happens to be, the same technique can be applied to headings and/or more complex pages.

You can also add breakpoints for your type to control line length, leading and hierarchy, because these are also affected when your container and type sizes change.

body {
   font-size: 100%;
   font-family:Georgia;
}

@media only screen and (max-width: 400px) {
   body { font-size:80%;}
 }

 

Overflow:hidden

Applying overflow: hidden allows you to clear the float from the previous element and keep the content running within the containers as the containers resize to fit a new screen environment. This trick is extremely useful for one of the common problems we face when coding with float based layouts, when the wrapper container doesn’t expand to the height of the child floating elements.

But overflow: hidden can also be very useful for images in your responsive web design. You can set a maximum height and crop the image. Put your image in a container and set the width of your image to 100%. Then set the max-height of the container to 450px and hide the overlap by setting the overflow to hidden.

.image-wrap {
    max-height: 450px;
    overflow: hidden;
    max-width: 800px;      
}

.image-wrap img {
    width: 100%;
}

@media only screen and (min-width: 1160px) {
    .image-wrap { max-width: 1000px }
}

If you now change the width of the container, you will see that the image adapts the container’s width but does not exceed the max-height (Read more about this technique: Overflow Image with vertical centering for Responsive Web Design).

Automatic line breaks in narrow columns with CSS 3

A problem that has always existed but has become more common lately as more people – thanks to the popularity of responsive web design – make their layouts adapt to narrow viewports, is the lack of automatic hyphenation in web browsers.

As columns of text become narrower, the risk of a single word being longer than the column width increases. When that happens, the text normally extends outside the column. The effect can be anything from just a slight visual glitch to unreadable text. Either way it’s something you don’t want to happen.

Luckily, CSS offers two properties that can help improve the situation: word-wrap and hyphens. By combining these two properties we can avoid text sticking out of their containers in almost all browsers. Just add the following declarations to a rule targeting any problematic elements:

-moz-hyphens:auto;
-ms-hyphens:auto;
-webkit-hyphens:auto;
hyphens:auto;
word-wrap:break-word;

Source

Full-size Background-Images

Since modern designs feature background images a lot, it’s important that they’re properly rendered on different viewing devices as well. To achieve full coverage of the screen by the background image the following CSS code can be used:

html {
    background: url(bg.jpg) no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Here ‘cover’ is the keyword from CSS3 specification which commands that background image is scaled proportionally covering the entire browser window.

Responsive Background-Images

A neat trick to make it possible for background-images to ‘fluidly’ resize keeping the same aspect ratio and without leaving space below or chopping off the image. The smart move is to set the height to 0 and work out the height depending on the aspect ratio of the image itself and use padding-bottom to reveal the image instead.

.background {
    display: block;
    height: 0;
    padding-bottom: 80%;
    background: url(images/image.jpg) no-repeat;
    background-size: 100%;
    text-indent: -9999px;
}

The percentage in the padding-bottom is the aspect ratio of your image. Divide the height by the width of the image, then multiply it by 100 and you’ve got your exact percentage. If the image height is bigger then the width you’ll have a percentage >100%!

Note: I’ve done an experiment with this technique and wrote a tutorial about how to serve different responsive (and Retina-friendly) background-images with various media-queries.

Multi-columns

There is a very new set of properties which allow for multicolumn creation within an element. These are new properties so you will need to use prefixes as they do not work in all browsers without them just yet. The properties are self explanatory: column-count is the amount of columns you’d like while column-gap is the size of the gap between the columns. Of course, there are other properties but these two are enough for you to get around.

@media all and (min-width: 900px) {
   #example p  {
  -webkit-column-count: 3;
  -webkit-column-gap: 1%; /* Saf3, Chrome*/
  -moz-column-count: 3;   
  -moz-column-gap: 1%; /* FF3.5+ */
  column-count: 3;        
  column-gap: 1%; /* Opera 11+*/
  }
}

@media all and (max-width: 900px) and (min-width: 600px) {
#example p  {
  -webkit-column-count: 2; /* Saf3, Chrome*/
  -webkit-column-gap: 4%; /* Saf3, Chrome*/
  -moz-column-count: 2; /* FF3.5+ */
  -moz-column-gap: 4%; /* FF3.5+ */
  column-count: 2; /* Opera 11+*/
  column-gap: 4%; /* Opera 11+*/
  }
}

CSS Flexible Box Layout Module

Flexbox is a recommendation in CSS3 that enables designers to control the arrangement of elements on a page with more finesse than contemporary CSS approaches which have become common because we didn’t have a better solution.

A Flexbox layout creates a relationship between its containing element — a <div>, for example — and the items the container encompasses. At its most fundamental, Flexbox arranges items in a line that points in any cardinal direction without changing the HTML. For more (and better) information about CSS3 Flexbox, please read: Using CSS flexible boxes

/* This is only an example how this CSS property can be used in your CSS file */
aside {
background-color: orange;
order: 4;
flex: 1 ;
}
.mainContent {
background-color: white;
order: 3;
flex: 2;
}
.extraDiv {
background-color: pink;
order: 2;
flex: 1;
}

Note: this CSS property has a limited support in modern browsers, so far it only works on Chrome 21+, Firefox (Gecko) 20.0+, Opera (& Opera Mobile) 12.1+, and Blackberry 10+.

 

Author: Jan Rajtoral

Jan Rajtoral AKA Gonzo the Great is the Founder of and Designer at gonzodesign, providing design services across the full spectrum of Brand Identity, Graphic Design, Print and Advertising Design & Website Design.

23 comments

on this article: “11 Useful CSS Code Snippets for Responsive Web Design”
  1. Great article Gonzo! Do you have any useful code snippets for serving up higher pixel density images? (aka Retina) I am torn between using Javascript libraries, media queries and SVG graphics but they all need their fallbacks.

    • Hi Christian,

      .. thanks, glad you liked it! Ha, you sound like me a couple of months ago .. concerning feeling torn apart how to serve crisp images/graphics for Retina. And lucky you, I have even written a lil’ about this topic: http://www.gonzoblog.nl/2012/12/24/wishing-you-a-responsive-and-retina-friendly-xmas/ (check the last part for Retina).

      Imho, making your images 2x and compressing it keeps the file size your images/graphics small (even smaller than 1:1 images at 80% compression, .. ehr? Yeah, really, did some experiments with this and it kicks butt!). Adding loads of CSS, 2 different images (normal and @2x), or even Javascript won’t do the overall performance of your site any good. Also management of your images stays easy in a fluid world, you just have to add 1 image and be good .. even on HD Displays ;-P

      Hope you’ll keep me posted which technique/method you’ll finally choose to serve crisp images to HD displays? Thanks for your comment, enjoy your day .. cheers & ciao!

      • Thanks Gonzo,

        That is how I’ve been doing things, except only on icons and detailed graphics rather than every type of image. Very useful information for developing Phonegap applications, pesky Retina. In future projects I will probably try out the 2x with heavy compression, my only worry is memory usage for larger images on mobile (longer load times!).

        • Hi Christian,

          Check the links in the article with my responsive background-image experiment, the 2x images with high compression (especially .jpg’s) have less kB’s than all those 1x images with 80% compression. Really, do some experiments with it, the results will knock your socks off!

          .. concerning icons and smaller graphic stuff, you should consider using iconfonts and SVG for that! For every new project I now make an unique icon font (via icomoon), keeping file size – and therefore loadtime – as small as possible and embedding via @font-face! The file size of an icon font easily beats every 2x image – even if heavily compressed – and makes it easy to add CSS properties (shadow, hover, etc.), use more sizes without needing to have more icon sizes, etc., etc. Not to mention icon fonts always stay sharp and crisp, .. even with an HD display on steroids ;-P

          For things like logos I want to use more SVGs with a simple Javascript (e.g. SVGeezy) for serving in stead of the SVG a .png/.jpg for the older browsers .. every browser that starts with IE (except the latest version ;-P). Still struggling with this one, cuz an 2x optimized logo (.jpg/.png) isn’t that huge on load time, neither is an SVG, but the Javascript gives me an extra http-request and could synchronous load that script what will stop all other elements of being loaded.

          Let me know what your findings are about the Retina-topic, okay! Enjoy your evening buddy, cheers & ciao!

  2. I try to make my website responsive for many time, and not work as I want. I will try your tutorial and hope successful to responsive my website. Thanks for the clue mate…

    • Hi Agus,

      yeah, it’s a bit of a mind shift designing responsive sites. Most important, imho, is a good planning at the beginning of your project! Anyhowz, wishing you luck and success, buddy, and please let me know when you’re done designing your site, I would love to have a look!

      Cheers & Ciao!

  3. I have a question. Why are you telling people to set the user-scalable=no? Doesn’t this mean that a user would not be able to pinch and zoom in case they can’t read the text on a web site?

    • Jonathan,

      I copied my meta-viewport from this blog (and a year and a half ago, when I coded this blog, this was the appropriate way to set up your meta-viewport. As I recall this ‘best practise’ was even preached by the mobile team of Yahoo), but it’s outdated now.

      Tho you make it sound as user-scalable=no is some kinda disease, .. there are some corner use cases for this, but you’re right that it does not make sense to do this on text-heavy sites as it impairs accessibility.

      Have a great day, ciao!

  4. You have a lot of great information here. However there is one thing you should NEVER do when creating a responsive site or even a site that will be viewed on a mobile device. That item is you should never set either maximum-scale=1 or user-scalable=no. You never know when a user needs to zoom into your page in order to read what you have displayed. There are plenty of people that need to zoom in as even 16px is not large enough for them to read on a hand held device. By setting user-scalable=no you are not allowing that. Same goes for maxiumum-scale.

    • Hi Jonathan,

      yep, thanks for pointing that out as well! I finally had the time to respond to the comments here, and as you can see this was pointed out by Tom Hermans as well (was not visible when you posted your comment). I reacted on that comment already, and even gave a reason why I f*cked up, haha!

      Anyhowz, tipping my hat to you too! Thanks for pointing that out .. Cheers & Ciao!

    • Hi Tom,

      thanks for the link, man! I quickly copied my gonzoblog viewport-meta in this article, not realising this meta is a year and a half old ;-P I was aware of the fact that disabling pinch zoom on mobile devices (by using maximum-scale=1.0) wasn’t a smart move .. guess I never re-checked my viewport meta here on the gonzoblog!? .. and yep, changed this as we speak!

      BTW: think I even can delete the initial-scale=1.0, cuz that’s the default in most browsers!? So thanks for the reminder Sir, I tip my hat to you! Cheers & Ciao buddy!

      • FYI, I had it at some point too in my “boilerplate”, picked up from “somewhere”, cause at sometime it was indeed in some advice (some blog authors just write anything hé :p :) )

        only to get mad at my own site (built on the very boilerplate) when I tried pinch and zoom.. oh, the irony, cursing at the dev ;)

        • Hi Tom,

          you know what it is with RWD, it’s so new we almost have to invent the wheel every day! Yesterday’s best practices become tomorrow’s common mistakes .. aah, well, you know how these thing go buddy ;-P

          Enjoy your day Tom and thanks for commenting, appreciated! Cheers & Ciao Amigo!

  5. Nice list, but first one I think you should edit.
    It is not a good thing to take away the user’s (default) control re: viewport resizing

    maximum scale and user-scalable no should not be in there..

  6. Great writeup Jan. I’ve used a few of these on my site (including multi-columns on large screens) and I’m quite impressed with the results. Keep up the great work!

    • Hi Rob,

      thanks for your comment! Just saw your site .. pretty impressive work Sir! And yeah, loving the multi-columns here too! ;-P Enjoy your day, cheers & ciao!

  7. I spent all morning trying to figure out how to make a background proper for a responsive design.

    Here is a question, is it better for speed to have one large image that is resized depending on breakpoints or to just have a small repeating image. I have a background with a texture.

    I just figure it is faster for a browser to load the image and then cache it.

    • Hi Susan,

      .. it totally depends on the background-image you wanna use, imho.

      If you have a huge background-photo (that should be crisp on all devices) you should a) compress your image – a bit more about this in this article, with some great links – and use CSS property background-size: cover; or b) compress your photos (could be different photos or the same picture in various dimensions) and serve a different responsive background-image in your various media-queries to decrease loading-time. A smaller image will have less kB than a big (desktop-size) background-image that is scaled down!

      If your background is ‘just’ a (seamless) texture I should go for a e.g. 100×100 px image and tile/repeat that image as your body background.

      .. or, use 2 backgrounds for your body/html? One background with the photo (different ways to do this) and your second background could be a tiled texture? But .. the effect what will happen here, is that your photo-background will scale and your tiled background most probably not, especially when it’s dimensions are smaller than your smallest viewport/resolution ;-P

      So Susan, hope I understood your dilemma right? But the thingie here is that you must try and keep file-size as small as possible for the mobile devices. But to compress your images is by far the best thing you can do, read more about that in this article

      Thanks for your comment Susan, cheers & ciao!

  8. Informative as always!
    Thanks a lot, finally got my personal responsive website to work : christian-fei.com :)

    • Hi Christian,

      .. thanks for your comment! Just saw your site, looking clean .. just one little advise (if I may so), give a little more margin or padding (whatever you wanna use) for your #content on smaller devices. There is almost no space in the side margins, it will increase readability and will give the text some more room to breathe .. just a thought, buddy.

      Cheers & Ciao!

      • Cool, thanks for pointing that out!
        I doubled the margin on the left,
        If you could take a minute and check again if it’s cool now, I would just appreciate that so much :)

        • Hi Christian,

          yep looks much cooler now! You could give the ‘tablet’ and ‘desktop’ version maybe some extra room too, it doesn’t have to be much tho! Ciao!

top