.. Your Daily Design Dosis

11 Useful CSS Code Snippets for Responsive Web Design

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.

Media Queries

CSS3 supports all of the same media types as CSS 2.1, such as screen, print and handheld, but has added dozens of new media features, including max-width, device-width, orientation 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:

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.

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.

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:

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:

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.

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

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.

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

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

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.

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

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

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.

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!

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.

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.

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!

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!

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