Learning Responsive Data Visualization - Christoph Korner - E-Book

Learning Responsive Data Visualization E-Book

Christoph Körner

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

Master the art of building responsive visualizations on the Web

About This Book

  • Learn the techniques for building data visualizations that work well for all screen sizes
  • Implement responsive techniques with popular libraries to get to grips with building responsive visualizations that work in the real world
  • Incorporate responsive workflow in your data visualization process to build visualizations that take a mobile-first approach.

Who This Book Is For

Web developers and data science professionals who want to make their visualizations work for smaller screen sizes. Some basic knowledge of JavaScript and Data visualization is expected.

What You Will Learn

  • Get familiar with responsive design for data visualizations
  • Understand the main concepts of D3.js to create interactive visualizations
  • Unleash the power of Bootstrap to create stunning and responsive visualizations for all screen resolutions
  • Implement Touch and Mouse interactions for mobile-first applications
  • Design Transitions and Animations that impress in portrait and landscape
  • Build a Responsive World Map using GeoJSON and D3.js

In Detail

Using D3.js and Responsive Design principles, you will not just be able to implement visualizations that look and feel awesome across all devices and screen resolutions, but you will also boost your productivity and reduce development time by making use of Bootstrap—the most popular framework for developing responsive web applications.

This book teaches the basics of scalable vector graphics (SVG), D3.js, and Bootstrap while focusing on Responsive Design as well as mobile-first visualizations; the reader will start by discovering Bootstrap and how it can be used for creating responsive applications, and then implement a basic bar chart in D3.js. You will learn about loading, parsing, and filtering data in JavaScript and then dive into creating a responsive visualization by using Media Queries, responsive interactions for Mobile and Desktop devices, and transitions to bring the visualization to life. In the following chapters, we build a fully responsive interactive map to display geographic data using GeoJSON and set up integration testing with Protractor to test the application across real devices using a mobile API gateway such as AWS Device Farm.

You will finish the journey by discovering the caveats of mobile-first applications and learn how to master cross-browser complications.

Style and approach

As the world shifts to mobile devices for consuming data on the Web, developers are faced with the unique challenge of making data visualizations work for their smaller screens. The growth of responsive web design enabled developers to adopt page layouts and media for smaller screens, but there is still little information available on how to adapt data visualizations for the smaller screens. This book fills this important gap and shows how responsive web design principles can be extended to create visualizations that work well regardless of the screen size, thereby allowing developers to build user-friendly visualizations that work well on all devices. In addition to covering some of the popular techniques and design patterns for building responsive visualizations, the book also shows readers how to implement these techniques with the help of some popular tools and libraries.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 288

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Learning Responsive Data Visualization
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Getting Started with Responsive Design, Bootstrap, and D3.js
What is Responsive Design?
Conditional CSS with Media Queries
Understanding Breakpoints
Having the right viewport
Relative Units – %, REM, and EM
Designing for mobile devices first
Bootstrap – a popular mobile first CSS framework
Including Bootstrap
Finding additional resources
Understanding grid layouts
Hiding elements on different screen resolutions
Using Bootstrap's Media Queries in LESS
Vector graphics in the browser with SVG
Raster/Pixel graphics with Canvas
Hardware-accelerated Pixel Graphics with WebGL
Vector graphics with SVG
Creating graphics with D3.js
Including D3.js
Finding additional resources
Summary
2. Creating a Bar Chart Using D3.js and SVG
Getting started with D3.js
Selecting and manipulating DOM elements
Manipulating SVG elements
Data-driven transformations
Data Binding and Dynamic Properties
Data Join – next-level data binding
Using the update pattern
Defining an Identifier for the elements
Drawing shapes with D3
Drawing Lines and Curves
Drawing Areas between curves
Drawing arcs
Creating Scales and Axis
Mapping data values to a Pixel Range with scales
Linear Scales for linear Mappings
Ordinal scale for Mapping non-numeric data
Time scales for Mapping time series data
Creating Axis
A simple bar chart
Summary
3. Loading, Filtering, and Grouping Data
Preprocessing data
Filtering data to remove outliers
Mapping data to access inner properties
Aggregate data to extract valuable information
Reduce functions in D3.js
Loading and parsing remote data
Parsing any string data
Splitting strings using Regular Expressions
Parsing dates from strings
Parsing and formatting numeric values
Grouping data
Summary
4. Making the Chart Responsive Using Bootstrap and Media Queries
Units and lengths in the browser
Units for absolute lengths
Units for relative lengths
Units for resolution
Mathematical expressions
Responsive charts
Using relative lengths in SVG
Conclusion about using relative lengths
Scaling the viewport
Prevent Strokes from Scaling
Preserving the Aspect Ratio
The conclusion of using Viewport scaling
Using the JavaScript resize event
The native resize event
Adapting the resolution of the data
The conclusion of using resize events
Using Bootstrap's Media Queries
Media Queries in CSS
Media Queries in LESS/SASS
Media Queries in JavaScript
Using Bootstrap's grid system
Summary
5. Building Responsive Interactions
Using an event system
Custom events in D3.js
Responsive events
Interaction areas
Creating interaction targets
Computing the nearest data point
Touch events
Mouse events
Panning and zooming
A simple zoom
An axis zoom
Summary
6. Designing Transitions and Animations
Is there a web standard for animations?
Animate SVG using SMIL
Animating HTML using CSS
Animating anything using JavaScript
Creating animations with JavaScript
Timers and intervals in D3
Interpolating attributes using D3
Easing – Animation progress over time
Bézier curves
Easing functions in D3
Transitions
Path transitions made easy
Attribute and style tweens for custom interpolation
Chained transitions
Shape tweens
Summary
7. Creating Maps and Cartographic Visualizations Using GeoJSON
Overview of cartographic visualizations
A geographic coordinate system
Projecting a sphere on a flat map
Which data can be displayed on a map?
Can we start now?
Data representation for topology and geographic features
GeoJSON – a format for geographic features
TopoJSON – GeoJSON for web visualizations
GeoJSON to TopoJSON via the server API
TopoJSON to GeoJSON via the Client API
Maps and projections
The Equirectangular projections
Orthographic projection
Albers projection
Spherical Mercator projection
Azimuthal Equidistant projection
Helpful tools for creating maps in D3
Color scales
The geographic shape generator
Graticule – grids on maps
Loading multiple resources
Types of geographic visualization
Symbol maps
Choropleth maps
Summary
8. Testing Responsive Visualizations
A guide on testing visualizations
Why should I care about testing?
The different types of test
Manual tests
Automated tests
Semi-automated tests
Unit tests
Integration tests
Continuous Integration
Test-driven development (TDD)
Manual testing and debugging
Testing and debugging locally
Changing Device Modes in a Chrome desktop browser
Emulating mobile devices
Syncing Real Devices using Browsersync
Remote-debugging responsive applications
Semi-automated visual Regression tests
Automated testing and Continuous Integration
Running tests on your local machine
Running unit tests using Karma
Integration testing using Protractor and Selenium
Running your tests in the cloud
A testing strategy for visualizations
Summary
9. Solving Cross-Browser Issues
A solution to cross-browser compatibility issues
Conditional comments for Internet Explorer
Detecting native features with Modernizr
Using Modernizr in JavaScript
Using Modernizr in CSS
Custom implementations of native features
Polyfill – implementing missing features
Shims – intercepting API calls
Wrappers – abstracting APIs
Compatibility of D3
Cross-browser Media Queries
Window.matchMedia() and its Polyfill
Min-width and max-width support via Respond.js
Media Queries in JavaScript with Enquire.js
Cross-browser SVG features
SVG animations
Using SVG filters
Clipping elements in SVG
Handle touch and mouse events with ease
Mouse and touch events
Breaking the event execution chain
Touch events in D3
A note on detecting Touch Devices
A hover state for touch
Pointer events – combining mouse, touch and pen
Disabling pointer events for elements
Summary
Index

Learning Responsive Data Visualization

Learning Responsive Data Visualization

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: March 2016

Production reference: 1180316

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-378-1

www.packtpub.com

Credits

Author

Christoph Körner

Reviewer

Sébastien Fragnaud

Commissioning Editor

Wilson D'souza

Acquisition Editor

Reshma Raman

Content Development Editor

Sachin Karnani

Technical Editor

Gebin George

Copy Editor

Yesha Gangani

Project Coordinator

Nikhil Nair

Proofreader

Safis Editing

Indexer

Monica Ajmera Mehta

Graphics

Disha Haria

Production Coordinator

Nilesh Mohite

Cover Work

Nilesh Mohite

About the Author

Christoph Körner, CTO and lead developer at GESIM, a start-up company, is a passionate software engineer, web enthusiast, and an active member of the JavaScript community with more than 5 years of experience in developing customer-oriented web applications. He is the author of Data Visualizations with D3 and AngularJS and is currently pursuing his master's degree in Visual Computing at Vienna Institute of Technology.

I want to thank my close friends, Firat Özdemir and Vidor Kanalas, for their continuous support and help, as well as my boss and colleague, Dietmar Wiegand, for supporting all my ideas and dreams. I also want to thank my girlfriend, Laura Andrea Rojas Padilla, who has always inspired, motivated, and supported me, as well as the whole team at Pack Publishing for believing in me and supervising me during the last 6 months.

About the Reviewer

Sébastien Fragnaud is a frontend engineer who works at Metamarkets. He creates beautiful UIs out of beautiful mockups. Before this, he worked for several different companies, but his focus was always the same: presenting data in a meaningful manner.

Deeply fond of reusable code, he's the author of n3-charts, a JavaScript library that provides an easy way to manipulate charts in AngularJS applications.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Preface

Data visualizations are the best way to understand complex information and data. The human brain perceives visual information easily; it can make connections and is able to understand the complete process easier than without visualizations.

I am always delighted with the positive feedback from users whenever they understand a complex system easily by looking at a data visualization, instead of going through explanatory text and raw data. With the power of the Web and modern browsers, I can share these visualizations with everyone and make them interactive and animated.

To power cross-browser interactive visualization, I didn't want any compromise with regards to performance, debugging, quality, and interactivity, which led me to SVG. After deciding for SVG, I looked for a framework for SVG transformations giving raw access to all its underlying standards while also providing a rich set of visualization features - the D3.js library provides all of these.

D3.js is a visualization toolkit that facilitates the generation and manipulation of web-based vector graphics and provides full access to underlying SVG standards. Moreover, animations and interactive visualizations change the way users perceive web applications, and D3.js offers everything you need to make a visualization interactive out of the box.

While this has been working for the last few years, I realized that users are increasingly accessing visualizations with their mobile devices, though mostly through smartphone and tables. On most tablets, visualizations looked good, though interactions did not work anymore. Smartphone users experienced this as well when they tried to zoom into a browser but it somehow interfered with the zoom of the visualization and randomly toggled interactive features instead. For me, this was the sign I needed to fix the problem.

With the rise of responsive web design, there were already plenty of ideas for creating cross-browser and cross-platform applications that adapt to a user's device, screen size, and resolution. Apart from this, modern browsers already provide solid CSS and JavaScript functionality to implement responsive designs for all kinds of web applications.

The only logical step for me was to combine rich tools in order to create responsive applications and introduce the same ideas into data visualizations. I want my visualizations to adapt to the user's device, screen size, and resolution while providing cross-platform interactivity for mouse and touch gestures. In this book, I will share my knowledge, experience, and best practices on responsive data visualizations with you.

What this book covers

Chapter 1, Getting Started with Responsive Design, Bootstrap, and D3.js, gets you on track with today's concepts, technologies, and frameworks to create responsive applications.

Chapter 2, Creating a Bar Chart Using D3.js and SVG, helps you get started with D3.js and its concepts. You will learn how to draw points, shapes, and simple bar charts by the end of this chapter.

Chapter 3, Loading, Filtering, and Grouping Data, guides you so that you can get the maximum information out of real-world data.

Chapter 4, Making the Chart Responsive Using Bootstrap and Media Queries, goes through all of the steps needed to make visualizations responsive and adapt them to user devices.

Chapter 5, Building Responsive Interactions, teaches you to add truly responsive interactions to your visualization, which also makes these great to use on user devices.

Chapter 6, Designing Transitions and Animations, teaches you to make a visualization appealing to look at by adding gorgeous transitions or custom animations.

Chapter 7, Creating Maps and Cartographic Visualizations Using GeoJSON, helps you get started with geographic data processing and then visualize this data in cartographic visualizations.

Chapter 8, Testing Responsive Visualizations, shows you how to test responsive visualizations both manually and in an automated manner, and covers both unit and end-to-end testing.

Chapter 9, Solving Cross-Browser Issues, helps you avoid the most common pitfalls when dealing with cross-browser compatibility issues for responsive visualizations.

What you need for this book

The first thing you need to get started with is a web browser and text editor, such as Sublime Text or Atom. Then, you need to install node.js (http://nodejs.org/)—which already includes the npm package manager—and the bower package manager (http://bower.io/). I will walk you through the installation of the required packages in the corresponding chapters.

For examples that require you to load data from your local hard drive, I would recommend that you install the http-server module (https://www.npmjs.com/package/http-server) to run all the examples from a local web server. An Internet connection is only required to install tools and libraries but not to run the examples.

Who this book is for

This book is intended for data scientists, developers, and motivated beginners to implement custom responsive data visualizations using vector graphics. Whether you already know a bit about SVG and vector graphics in a browser or you have never used any visualization library before, you will be able to master the data-driven techniques of D3. In either case, this book will get you up and running as quickly as possible and also challenges you if you have already worked with D3.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

Downloading the color images of this book

We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/LearningResponsiveDataVisualization_ColoredImages.pdf.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. Getting Started with Responsive Design, Bootstrap, and D3.js

The best way to understand data is to visualize it and explore it using an interactive visualization. In this book, we are going to build such an interactive visualization (actually many of them) using the latest techniques and web technologies. To make the information accessible across all devices, we are going to make the visualizations responsive. However, before we can start, we need to understand what this actually means. We also want to reuse some existing frameworks to not just do a great job but also work in an efficient way.

This chapter serves as an introduction to the methods, technologies, and frameworks that we will use throughout the book, and it will help you understand why we are using them to create data visualizations and how they work together.

In this chapter you will learn the following:

What exactly is Responsive Design and how can it be applied to create visualizations that work across all different screen sizes and resolutionsWhat is a Media Query and how it can be used to design visualizations for various devicesWhy and how we use Bootstrap to build the visualization on existing componentsWhy we use vector graphics, such as SVG, for the webWhy we use D3.js for data manipulation and graphics creation

First, you will learn about Responsive Design and how it can be used to design a visualization for various screen sizes and resolutions. Then, we will discuss the importance of some key technologies such as CSS3 (especially Media Queries) and HTML5 (especially the viewport meta tag).

In the following chapter, we will get acquainted to the popular CSS and HTML framework called Bootstrap. Don't worry if you have never heard about it; it helps us to build the application on the existing and well-tested components, such as grids and LESS Media Queries.

In the last section of this chapter, you will learn about Scalable Vector Graphics (SVG) in the browser; and you will understand why and when it is great to use vector graphics for visualizations. Then, we will see a brief introduction to D3.js, which is a versatile JavaScript library for data transformations and graphics generation. At the end of this chapter, you will understand why SVG is a great choice for designing interactive responsive visualizations for the web.

What is Responsive Design?

Responsive Design is a method for designing applications that can adapt their appearance and behavior to the user's device. It makes the application look and feel good across all different devices, and most often, it makes them usable on all devices.

An important paradigm in Responsive Design is to use relative dimensions instead of fixed widths, heights, margins, paddings, and font sizes throughout all the application to adapt the design to the various types of devices.

For web browsers, Responsive Design was enabled through CSS3 and HTML5 features, such as Media Queries, the viewport meta tag, and new dimension units.

Conditional CSS with Media Queries

Media Queries were introduced in CSS3 as a more flexible extension of Media Types. They allow the developer to apply conditional CSS styles only when a statement (a so-called query) matches a certain CSS property (so-called Media Features) and a Media Type. A typical Media Query has the following structure:

@media [Media Type [and|not|only]] (Media Feature) { ... }

Here is a small selection of properties that can be used as Media Features:

width, min-width, and max-widthheight, min-height, and max-heightdevice-width, min-device-width, and max-device-widthdevice-height, min-device-height, and max-device-heightresolution, min-resolution, and max-resolution

Note

A complete list of Media Features and Types can be found on MDN at https://developer.mozilla.org/de/docs/Web/CSS/Media_Queries/Using_media_queries.

In Responsive Design, we are mostly interested in querying the min-width or max-width property to apply different styles to devices that have different widths.

Let's see an example where we can apply a different background color depending on the minimal width of the browser window:

div { background-color: blue; } @media screen and (min-width: 992px) { div { background-color: red; } }

In the preceding example, all the div elements in the page have the background color red as long as the browser window's width is larger or equal to, 992 px (see the following figure):

Browser window width larger than 992px

Once the window width is smaller than 992 px, the background color of the div elements jumps to blue (see the following figure):

Browser window with width smaller than 992px

As we can see in the following figure, Media Queries are supported across all major browsers and Internet Explorer starting from version 9:

Cross-browser compatibility Media Queries from http://caniuse.com/#feat=css-mediaqueries

Understanding Breakpoints

In Responsive Design, we call a state when a certain layout and Media Query is active, and we call a breakpoint the transition from one state to another.

Let's look at an example. First, we define some screen dimensions for the following devices:

<768px is for phones768px-992px is for tablets992px-1200px is for desktops≥1200px is for large devices and TVs

Create a CSS snippet using Media Queries for these device dimensions:

/* phones, default no query */ /* tablets */ @media (min-width: 768px) { ... } /* desktops */ @media (min-width: 992px) { ...} /* large devices */ @media (min-width: 1200px) { ... }

In the preceding code, we defined four states with three breakpoints between these states where each state corresponds to a typical screen dimension and device type.

We can also see these breakpoints by reducing the size of a browser window while looking at a responsive web page; we observe how the design breaks at a certain width of the browser window. In the following figure, the breakpoint is visualized as a dashed line, showing the moment when one state breaks into a new one:

Breakpoint in Responsive Design

We can observe the same effect when we look at the Google Plus web page in the following figure. In the first two figures, the size of browser window changes, but the three-column layout stays the same. In the third image, the design breaks into a new layout with only two columns:

Breakpoints of the Google Plus page

Having the right viewport

Across mobile and desktop devices, there exists a vast variety of different pixel densities and screen resolutions. Displays with much higher resolution would render pages much smaller than displays with a lower resolution; this immediately leads to readability problems. To prevent this effect and fit bigger pages into smaller screens, a virtual window—the so-called viewport (the visible area of a web page)—was introduced. This allowed websites to render in the correct pixel resolution and scale to the full device width for maximal accessibility; however, developers had no control over this device-specific setting. Later, in HTML5, the viewportmeta tag was introduced in order to give developers full control over these viewport settings.

Today, a mobile-optimized application usually defines the following viewport tag in the head section of the web page to render the website normally and scale the content to the width of the device:

<meta name="viewport" content="width=device-width, initial-scale=1">

Note

More information about all the valid viewport options can be found on MDN at https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag.

Relative Units – %, REM, and EM

When dealing with Responsive Design, it is always a good idea to use relative units to describe the element's dimensions based on its parent element. Thus, when the parent container changes the size, all children elements adapt their sizes accordingly.

The most popular unit for relative dimensions is %, which defines the dimension based on a certain percent of the next absolute positioned parent element.

However, there are more useful units to describe relative dimensions; for example, the following two are based on the font-size:

em: This is relative to the font size of the elementrem: This is relative to the font size of the root element

These units have a big advantage; they are affected by the changes of the font-size setting in the browser. A simple example can be the adaption of the paddings when the user increases the font size of the browser.

Note

A short summary and explanation of all different CSS units can be found on MDN at https://developer.mozilla.org/de/docs/Web/CSS/length.

Designing for mobile devices first

Responsive applications should look and feel great (or work at all) on a huge number of devices with a huge number of different screen sizes and resolutions; they usually run on mobile devices as well as big TV screens. Thus, in the beginning of a project, every developer has to choose an approach to design the responsive application to master this transition; in general, we distinguish between the following methods:

Mobile firstDesktop first

In the desktop first method, we design for desktop devices and mouse input first, then we adjust and scale the design down for mobile devices and touch interactions. This often results in a web application with a reduced functionality for mobile devices due to a much smaller screen dimension and the lack of touch support.

In the mobile first method, we design for mobile devices and touch interactions first, and then we adjust and scale the design up for bigger devices and mouse interactions. This approach makes sure that mobile devices support a complete set of features, which can even be used on desktop clients.

Both methods are equally correct, accepted, and popular nowadays. The only exception is that mobile first became a buzzword due to an increase of mobile devices accessing the web during the previous years. Throughout the book, we will choose a mobile first approach and design for mobile devices and touch support. However, we will, of course, extend the visualizations to support mouse input and bigger screens. That's what the responsive design is all about.

Bootstrap – a popular mobile first CSS framework

If we want to create responsive mobile first web applications, we usually don't want to start from zero and re-implement common patterns and components; we would rather want to reuse some well-tested, existing components.

Bootstrap is a very popular HTML and CSS framework built by former Twitter employees for easy, fast, and modern frontend development; it provides loads of responsive CSS and LESS layouts as well as a huge collection of HTML and JavaScript components. Thanks to its MIT license, it can be used in open source and commercial software.

The current stable version 3.3.5 includes LESS styling with these features:

Containers and grids (static and fluid)Responsive helpers (hiding and showing elements on different breakpoints)LESS mixins and variable declarationsStyles for common components such as forms, input fields, and tablesIcons, HTML, and JavaScript components

Note

A complete list of features can be found on the Bootstrap website at http://getbootstrap.com/.

The new version 4 (which is currently in the alpha stage) will be shipped with SASS layouts and loads of other great features and improvements:

Note

There also exists an official fork for the SASS precompiler on GitHub at https://github.com/twbs/bootstrap-sass.

All units are in rem an emA new xl grid tier is addedOptional flexbox supportA Reboot module is available to reset default browser styles

Note

A complete list of new features can be found on the Bootstrap blog at http://blog.getbootstrap.com/2015/08/19/bootstrap-4-alpha/.

Throughout this book, we will use Bootstrap 3.3.5 version (with LESS) for all the examples and explanations if they are not stated differently. We will also give some hints about the latest version where it is appropriate.

Including Bootstrap

Make sure you have the Bower package manager installed; this can be done by running the following command from the terminal:

npm install -g bower

Note

More information about the Bower package manager can be found on its website at http://bower.io/.

Throughout this book, we will make use of only the CSS components of Bootstrap and thus we only need to include the bootstrap.css file to our project. There are multiple ways of doing so:

Use the package manager called bower (recommended)—First, fetch the library by running the following command from the terminal—bower install bootstrap#3.3.5. Then, link the minified CSS file from the bower_components/ directory in the head section of the web page: <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">.Use a Content Delivery Network (CDN), such as MaxCDN (this requires an active Internet connection while developing). Simply include the minified CSS file from the CDN in the head section of the web page: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">.Manually, download the 3.3.5 release from GitHub (https://github.com/twbs/bootstrap/releases) and unzip it into the libs/ directory. Then, link the minified CSS file from the libs/ directory in the head section of the web page: <link rel="stylesheet" href="libs/bootstrap/dist/css/bootstrap.min.css">.

I strongly recommend using the bower package manager to manage your frontend dependencies (or similar ones, such as npm or component). However, in the examples of this book, we will link Bootstrap directly from MaxCDN for simplicity reasons; therefore, all examples in the source of the book require an active Internet connection.

Finding additional resources

The ultimate resource for Bootstrap is the documentation that can be found at http://getbootstrap.com/getting-started/. Here, you will also find examples and templates using the Bootstrap framework.

For more detailed information and examples, I recommend reading the Unraveling Bootstrap 3.3 book by Istvan Novak.

Understanding grid layouts

A popular component to organize elements in an application or visualization is a grid layout. For responsive design in particular, we are mostly interested in grid layouts that adapt their columns to the screen resolution of the client. In the following figure, there's an example of a responsive grid layout with three columns per row on a desktop device and one column per row on a mobile device:

Simple Responsive grid, left: desktop, right: mobile

We then distinguish two different types of responsive grids that adapt the number of columns to the screen resolution of the client:

Normal grids with a fixed width per breakpoint (see following figure on the left)Fluid grids that always scale to the full width of the current breakpoint (see the following figure on the right)

Grid types—left: grid with fixed width, right: fluid grid

It's actually quite simple to build a grid system yourself; let's first take a look at how to create a fluid grid layout, and afterwards, we will better understand how we can use Bootstrap components to get things done quickly and properly.

If we think about a grid as a (flexible) table layout, we need two basic components: rows and columns. A popular approach is to use the 12-column grid where we divide the width of a row into 12 columns and define column combinations that sum up to the full width of 12. The following figure illustrates some of these combinations: 12 columns of width 1, 6 columns of width 2, 4 columns of width 3, and so on. Also other combinations that sum up to 12 are allowed, such as 2, 6 and 4 or 1, 10 and 1 and many more.

Grid layout with 12 columns

Let's start and build the .row class that spans to the full width of the parent element:

.row { position: relative; width: 100%; }

Next, we want to create column classes .col-1, .col-2, .…, and .col-12 that define the width of the column in the percent relative to the width of the row. We define a text wrap with the floatattribute and add padding for the cells. The float attribute indicates that the block element should not appear in the original flow but "float" on the left side. By doing so, we align the elements in the same line instead of placing them into the normal text flow: