HTML5 and CSS3 Responsive Web Design Cookbook

HTML5 and CSS3 Responsive Web Design Cookbook Learn the secrets of developing responsive websites capable of interfacing with today's mobile Internet devices Benjamin LaGrone BIRMINGHAM - MUMBAI HTML5 and CSS3 Responsive Web Design Cookbook Copyright © 2013 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: May 2013 Production Reference: 1160513 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-84969-544-2 Cover Image by Duraid Fatouhi ( Credits Author Benjamin LaGrone Reviewers Dale Cruse Ed Henderson Rokesh Jankie Acquisition Editor Edward Gordon Lead Technical Editors Savio Jose Neeshma Ramakrishnan Technical Editors Ishita Malhi Hardik Soni Nitee Shetty Project Coordinator Arshad Sopariwala Proofreader Amy Guest Indexer Tejal R. Soni Production Coordinator Nitesh Thakur Cover Work Nitesh Thakur About the Author Benjamin LaGrone is a web developer who lives and works in Texas. He got his start in programming at the age of 6 when he took his first computer class at The Houston Museum of Natural Science. His first program was “choose your own adventure book”, written in BASIC; he has fond memories of the days when software needed you to write line numbers. Fast forward to about thirty years later; after deciding that computers are here to stay, Ben has made a career combining some of his favorite things—art and coding; creating art from code. One of his favorite projects was using the GMaps API to map pathologies to chromosomes for cancer research. Fascinated with mobile devices for a long time, Ben thinks that the Responsive Web is one of the most exciting, yet long time coming, new aspects of web development. He now works in a SAAS development shop and is the mobile and Responsive Web evangelist for the team. When he’s not working on some Internet project, Ben spends his time building robots, tinkering with machines, drinking coffee, surfing, and teaching Kuk Sool martial arts. This book could not have been written without the patience and support of my loving wife, Hannah, and my two beautiful daughters, Daphne and Darby. Thank you. About the Reviewers Dale Cruse is the author of HTML5 Multimedia Development and has worked as a technical editor on several other HTML5 books. He started his career in 1995 as a U.S. Army photojournalist. Since going purely digital on, he’s created web and mobile experiences for some of the most well-known clients in the world, including 20th Century Fox, Bloomingdale’s, and MINI Cooper. Currently, he juggles between being a senior frontend developer at Allen & Gerritsen and a New York Yankees fan in South Boston. An in-demand speaker, you can’t get him to shut up on Twitter at @dalecruse. Ed Henderson was born and raised in Scotland, and is an experienced human being, with a love for designing, building, and making and breaking things online. Not afraid to get his hands dirty and his feet wet, he is open to new technologies as long as they are useful and/or fun. Ed has a real degree in Computer Science, has run his own business, worked freelance, been employed, and been a consultant. He is now employed as Senior Software Engineer for POPSUGAR in San Francisco, California, USA. He has vast experience in all aspects of the industry, from web pages and apps to social media. Ed has also reviewed and written a number of books. Ed thrives on coming up with fresh ideas. Making a difference and turning one of those ideas into useful, working “things” is what floats Ed’s boat. Away from the crazy world of the Web, Ed has run the Edinburgh Marathon and abseiled down a lighthouse, raising thousands of pounds for charity. He captained his local Scottish rugby team for three seasons, winning the championship as top scorer and reaching the final of a national competition. You may not know that Ed is the Dad from Jack Draws Anything ( and the winner of the prestigious .net magazine Social Campaign of the Year (2011) award. Ed lives in Corte Madera, California, USA (just 15 minutes from San Francisco) with the rest of Team Hendo: his amazing wife Rose and sidekicks Jack, Toby, and Noah. Ed likes cake, bacon, cider, and talking about himself in the third person. Rokesh Jankie graduated with a Masters degree in Computer Science from Leiden University, the Netherlands, in 1998. His field of specialization was Algorithms and NP-complete problems. Scheduling problems can be NP-complete, and that’s the area he focused on. After that, he started working for the University of Leiden. He then went on to work with ORTEC consultants, Ponte Vecchio, and later, with Qualogy. At Qualogy, he used his experience thus far to set up a product. Qualogy works in the fields of Oracle and Java technologies. With the current set of technologies, interesting products can be delivered; that is QAFE (see for more info). The company that he works for now is specialized in Oracle and Java technologies. As head of the product development department and CTO of QAFE Inc., his focus is on the future of web application development. At the company, modern technologies (such as HTML5, Google APIs, AngularJS, NodeJS, and Java) are used, and close contact is kept with some excellent people at Google to make things work. He has also reviewed the books HTML5 Canvas Cookbook by Packt Publishing and Dart in Action by Manning Publications Co. I’m very honored and grateful that I was contacted to review this book. Savio Jose gave me the opportunity to review the book. It always feels good to be part of the next big thing on the Web (HTML5, CSS3, and JavaScript) in this way and for this particular topic. The future of web applications looks very promising. Support files, eBooks, discount offers and more You might want to visit for support files and downloads related to your book. 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 and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details. At, 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. Do you need instant solutions to your IT questions? PacktLib is Packt’s online digital book library. Here, you can access, read and search across Packt’s entire library of books. Why Subscribe? ff Fully searchable across every book published by Packt ff Copy and paste, print and bookmark content ff On demand and accessible via web browser Free Access for Packt account holders If you have an account with Packt at, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface 1 Chapter 1: Responsive Elements and Media 5 Introduction 5 Resizing an image using percent width 6 Responsive images using the cookie and JavaScript 8 Making your video respond to your screen width 10 Resizing an image using media queries 13 Changing your navigation with media queries 14 Making a responsive padding based on size 19 Making a CSS3 button glow for a loading element 21 Chapter 2: Responsive Typography 27 Introduction 27 Creating fluid, responsive typography 28 Making a text shadow with canvas 29 Making an inner and outer shadow with canvas 31 Rotating your text with canvas 33 Rotating your text with CSS3 34 Making 3D text with CSS3 36 Adding texture to your text with text masking 38 Styling alternating rows with the nth positional pseudo class 39 Adding characters before and after pseudo elements 41 Making a button with a relative font size 42 Adding a shadow to your font 44 Curving a corner with border radius 46 ii Table of Contents Chapter 3: Responsive Layout 49 Introduction 49 Responsive layout with the min-width and max-width properties 49 Controlling your layout with relative padding 52 Adding a media query to your CSS 55 Creating a responsive width layout with media queries 59 Changing image sizes with media queries 64 Hiding an element with media queries 66 Making a smoothly transitioning responsive layout 68 Chapter 4: Using Responsive Frameworks 79 Introduction 79 Using the Fluid 960 grid layout 80 Using the Blueprint grid layout 84 Fluid layout using the rule of thirds 88 Trying Gumby, a responsive 960 grid 93 The Bootstrap framework makes responsive layouts easy 99 Chapter 5: Making Mobile-first Web Applications 105 Introduction 105 Using the Safari Developer Tools' User Agent switcher 106 Masking your user agent in Chrome with a plugin 109 Using browser resizing plugins 112 Learning the viewport and its options 113 Adding tags for jQuery Mobile 116 Adding a second page in jQuery Mobile 119 Making a list element in jQuery Mobile 122 Adding a mobile, native-looking button with jQuery Mobile 129 Adding a mobile stylesheet for mobile browsers only using media queries 135 Adding JavaScript for mobile browsers only 137 Chapter 6: Optimizing Responsive Content 139 Introduction 139 Responsive testing using IE's Developer Tools 140 Browser testing – using plugins 143 Development environments – getting a free IDE 149 Virtualization – downloading VirtualBox 152 Getting a browser resizer for Chrome 156 iii Table of Contents Chapter 7: Unobtrusive JavaScript 161 Introduction 161 Writing "Hello World" unobtrusively 161 Creating a glowing "submit" button with the event listener 165 Making a button stand out when you hover over it 169 Resizing an element with unobtrusive jQuery 173 Masking a password with unobtrusive JavaScript 177 Using an event listener to animate an image shadow 179 Index 185 iv Table of Contents Preface HTML5 and CSS3 Responsive Web Design Cookbook gives developers a new toolbox for staying connected with this new skillset. Using the clear instructions given in the book, you can apply and create responsive applications and give your web project the latest design and development advantages for mobile devices. Using real-world examples, this book presents practical how-to recipes for site enhancements with a lighthearted, easy-to-understand tone. Gain a real understanding of Responsive Web Design and how to create an optimized display for an array of devices. The topics in this book include responsive elements and media, responsive typography, responsive layouts, using media queries, utilizing modern responsive frameworks, developing mobile-first web applications, optimizing responsive content, and achieving unobtrusive interaction using JavaScript and jQuery. Each recipe features actual lines of code that you can apply. What this book covers Chapter 1, Responsive Elements and Media, covers the creation of elements that optimize to mobile devices or desktop computers. Chapter 2, Responsive Typography, teaches you about using fluid typography, creating cool text effects, and creating text that stands out on your screen through the HTML5 canvas and CSS3. Chapter 3, Responsive Layout, teaches you how to create responsive layouts that you can really use in your projects. You will learn about using viewport and media queries to make your web project respond to different viewport sizes and types. Chapter 4, Using Responsive Frameworks, teaches you how to use new frameworks to deploy responsive sites with the latest responsive methods and interactions quickly and reliably, and how to turn old static frameworks into responsive ones. Chapter 5, Making Mobile-first Web Applications, teaches you how to make mobile web versions of your web application, which are optimized to be mobile-first, with jQuery Mobile, and how to optimize for the desktop viewport. Preface 2 Chapter 6, Optimizing Responsive Content, teaches you about getting and using all the tools you need to build and test your responsive web project. Chapter 7, Unobtrusive JavaScript, teaches you how to write JavaScript that lives out of your web page so that you can have thoughtful, responsive interactions for different devices. What you need for this book You will need an IDE (integrated development environment); NetBeans or Eclipse is recommended (there are instructions on how to get one inside), image editing software such as Photoshop or GIMP, a web host, and a local web server such as Apache or a local hosting application such as XAMPP or MAMPP. Who this book is for This book, for all of today’s wireless Internet devices, is for web developers seeking innovative techniques that deliver fast, intuitive interfacing with the latest mobile Internet devices. Conventions In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: “ The height: auto property acts to preserve the aspect ratio of the image.” A block of code is set as follows:

Loremipsum dolor sit amet…


Loremipsum dolor sit amet

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

I think, therefore I am

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: “However, what I really want is a large image, so I click on Search tools, and then on Any Size, which I change to Large.”. Warnings or important notes appear in a box like this. Tips and tricks appear like this. Reader feedback Feedback from our readers is always welcome. Let us know what you think about this book— what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of. To send us general feedback, simply send an e-mail to, and mention the book title via 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 on 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. Preface 4 Downloading the example code You can download the example code files for all Packt books you have purchased from your account at If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you. 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 would 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, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from Piracy Piracy of copyright 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 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 You can contact us at if you are having a problem with any aspect of the book, and we will do our best to address it. 1 Responsive Elements and Media In this chapter, you will learn about: ff Resizing an image using percent width ff Responsive images using the cookie and JavaScript ff Making your video respond to your screen width ff Resizing an image using media queries ff Changing your navigation with media queries ff Making a responsive padding based on size ff Making a CSS3 button glow for a loading element Introduction The responsiveness website design and media is one of the most exciting things to happen to web development since ASCII art appeared on bulletin boards back when I was a school boy. The new cool features of HTML5, CSS3, and jQuery have brought new life to the old web in ways that have brought back the fun and really gets the Web audiences excited for using your applications. This chapter contains several recipes that will help you create responsive HTML elements and different media. Some recipes are easy and some are more challenging. All of the code used for the responsive web design elements is provided inside the book, therefore nothing inside will be impossible to accomplish. Each and all of the responsive web design recipes will help you optimize your website's presentation to create an amazing responsive web experience for your audience no matter what device type or size you are using. Responsive Elements and Media 6 Resizing an image using percent width This method relies on client-side coding for resizing a large image. It serves only one image to the client and asks it to render the image according to the size of the browser's window. This is usually the preferable method when you are confident that the clients have the bandwidth to download the image without causing the page to load slowly. Getting ready First you will need an image. To find a high-quality image, use Google Image Search. A search for robots, for example, the search gives me 158,000,000 results, which is pretty good. However, what I really want is a large image, so I click on Search tools, and then click on Any Size, which I change to Large. I still have 4,960,000 images to choose from. The image should be resized to match the largest scale viewable. Open it in your image-editing software. If you don't have an image-editing software already, there are many free ones, go get one. Gimp is a powerful image-editing software and it's open source, or free to download. Go to to get this powerful open source image-editing software. How to do it… Once you have your image-editing software, open the image in it and change the image's width to 300px. Save your new image and then move or upload the image to your web directory. Your HTML should contain your image and some text to demonstrate the responsive effect. If you do not have time to write your life story, you can go back to the Internet and get some sample text from an Ipsum generator. Go to and generate a paragraph of Ipsum text.

Loremipsum dolor sit amet…

robots image

Loremipsum dolor sit amet

Your CSS should include a class for your paragraph and one for your image and an image wrapper. Float the paragraph to the left and give it a width of 60%, and the image wrapper with a width of 40%. p.text { float:left; Chapter 1 7 width:60%; } div.img-wrap{ float:right; width:40%; } This creates a fluid layout, but does not yet do anything to create a responsive image. The image will stay at a static width of 300px until you add the following CSS. Then, add a new class to the CSS for the image. Assign it a max-width value of 100%. This allows the width to adjust to the browser width changes. Next, add a dynamic height property to the class. img.responsive { max-width: 100%; height: auto; } This creates an image that responds to the browser window's width with an optimized version of that image for the audience. Downloading the example code You can download the example code files for all Packt books you have purchased from your account at 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. How it works… The responsive property of the image CSS forces it to take 100 percent of its parent element. When the parent element's width changes, the image changes to fill in that width. The height: auto property acts to preserve the aspect ratio of the image. See also ff The Responsive images using the cookie and JavaScript recipe ff The Making a responsive padding based on size recipe Responsive Elements and Media 8 Responsive images using the cookie and JavaScript A responsive image's width can be delivered through complicated server logic. Sometimes because of the requirements you cannot achieve the desired results through the easiest method. The percent-width method relies on the client side for image resizing of a large image file. This method provides a server-side delivery of the properly sized image you request. It may reduce the server load and bandwidth and help you with long loading, if you are concerned with slow loading affecting the performance of your website. Getting ready These methods require your server to perform some sort of logic function on it. Firstly, it requires PHP on your server. It also requires you to create three different sized versions of the image and serve them to the client as requested. How to do it… The JavaScript is simple. It creates a cookie based on your device's screen dimensions. When the client makes a request to the server for an image, it fires the PHP code to deliver the appropriate image. Now, on your server, create an images folder in the web directory and create a PHP file (index.php) with the following code in it: 0) { $theExt = pathinfo($img, PATHINFO_EXTENSION); // for Low resolution screen if ($screen_width>= 1024) { $output = substr_replace($img, '-med', -strlen($theExt)-1, } // for Medium resolution screen else if ($screen_width<= 800) { $output = substr_replace($img, '-low', -strlen($theExt)-1, 0); } // check if file exists if (isset($output) &&file_exists($output)) { $img = $output; } } // return the image file; readfile($img); } ?> Now with your image-editing software, open your large image and create two smaller versions of it. If the original version is 300px, then make the next two copies 200px and 100px. Then, name them robot.png, robot-med.png, and robot-low.png respectively. Upload these three images into the images folder. Last, but not least, put the following HTML file in your server's document root: Responsive Images robot image Responsive Elements and Media 10 You can see the recipe in action in the following screenshot: While this method is limited to delivering a specific image for each screen size, and is not fluidly dynamic, it does provide the same functionality on the server side as a CSS media query. You can style the served image with CSS or animate it with JavaScript. It can be used with a combination of methods to provide responsive content. The code for this recipe was originally created by the clever folks at articoli/responsive-images-con-i-cookie/. How it works… The HTML file first creates a cookie describing your device's screen dimensions. When the image element calls the PHP file it works like an include statement in PHP. The PHP file first checks for the file to exist, then reads the cookie for the screen width, and delivers the appropriate-sized version of the image. Making your video respond to your screen width The streaming of video can also be responsive. You can easily embed an HTML5 video in your page and make it responsive. The video tag easily supports using a percent width. However, it requires that you have the video source on your website's host. If you have this available, this is easy. However, using a video-hosting site, such as YouTube or Vimeo, has many advantages over hosting it yourself. First, there is the bandwidth issue, you may have bandwidth or disk space limits on your hosting server. Additionally, video-hosting sites make the upload conversion to a usable web video surprisingly easy, compared to using only your own resources. Getting ready The video-hosting sites allow you to embed an iFrame or object code snippet in your page to stream the video on your site. This won't work inside the video tag. So, to make it responsive, there is a more complex, but still easy method. How to do it… Wrap the video-source snippet in an HTML containing the div element and give it a 50 to 60 percent padding on the bottom and relative positions. Then give its child element, the video iFrame object, a 100% width and 100% height, and an absolute position. This makes the iFrame object completely fill in the parent element. The following is the HTML code that uses an iframe tag to get a video from Vimeo:
The following is the HTML code using the older YouTube object with markup:
Responsive Elements and Media 12
Both video types use the same CSS: .video-wrap { position:relative; padding-bottom: 55%; padding-top: 30px; height: 0; overflow:hidden; } .video-wrap iframe, .video-wrap object, .video-wrap embed { position:absolute; top:0; width:100%; height:100%; } You might not want the video to take up the entire width of the page. In this case, you can limit the width of the video using width and max-width. Then, wrap the video-wrap element with the another div element and assign a fixed width value and max-width:100%.
.video-outer-wrap { width: 500px; max-width:100%; } This recipe will work on all modern browsers. Chapter 1 13 How it works… This method is called Intrinsic Ratios for Videos, created by Thierry Koblentz on A List Apart. You wrap the video inside an element that has an intrinsic aspect ratio, and then give the video an absolute position. This locks the aspect ratio, while allowing the size to be fluid. Resizing an image using media queries The media query is another useful and highly customizable method for responsive images. This is different than responsive fluid width achieved by the percent-width method. Your design may require some specific image widths for different screen size ranges and a fluid width would break your design. Getting ready This method only requires one image, and makes the client's browser resize the image instead of the server. How to do it… The HTML code is simple, using the standard image tag, create an image element, as follows: robot image To start with a simple version, create a media query that will detect the browser window's size and deliver a larger image for browser screens larger than 1024px, and a smaller image for smaller browser windows. First the media query, it looks for the media type screen, and then the screen size. When the media query is satisfied the browser will render the CSS inside the brackets. @media screen and ( max-width: 1024px ) {…} @media screen and ( min-width: 1025px ) {…} Now, add a class to your image tag. The class will respond differently in different media queries, as shown in the following code line: robot image Adding the CSS class to each media query with a different size will make the browser render the desired image size to each differently sized browser window. The media query can coexist with other CSS classes. Then, outside of the media queries, add a CSS class for the image with height:auto. This will work for both media queries with only adding one line of CSS. @media screen and ( max-width: 1024px ) { img.responsive { width: 200px; } Responsive Elements and Media 14 } @media screen and ( min-width: 1025px) { img.responsive { width: 300px;} } img.responsive { height: auto; } To make the image respond to multiple ranges you can combine the max-width and min-width media queries. To specify an image size for browser windows, sized between 1024px and 1280px, add a media query for screen, 1024px as min-width, and 1280px as max-width. @media screen and ( max-width: 1024px ) { img.responsive { width: 200px; } } @media screen and ( min-width:1025px ) and ( max-width: 1280px ) { img.responsive { width: 300px; } } @media screen and ( min-width: 1081px ) { img.responsive { width: 400px; } } img.responsive { height: auto; } You can specify many different image sizes for many different browser window sizes with the media query method. How it works... The media query of CSS3 gives your CSS logical conditions based on the browser's viewport properties, and can render different styles based on the browser's window properties. This recipe takes advantage of this by setting a different image width for many different browser's window sizes. Thus delivering a responsive image size, you can control with a high degree of granularity. Changing your navigation with media queries The media query can do more than just resizing images. You can use the media query to deliver a much more dynamic web page to your viewers. You can display a responsive menu based on different screen sizes using media queries. Getting ready To make a responsive menu system, using two different menus we will display a dynamic menu for three different browser window sizes. Chapter 1 15 How to do it… For the smaller browser windows, and especially for mobile devices and tablets, create a simple select menu that only takes up a small amount of vertical space. This menu uses an HTML form element for the navigation options that fires a JavaScript code to load the new page on selection.
For the larger browser window sizes, create a simple ul list element that can be styled through CSS. This menu will receive a different layout and look from the different media queries. This menu is added to the same page following the select menu: To make the menu responsive, create a media query for the target browser window sizes. For browser windows smaller than 800px, the CSS will display only the select form inside the div element with the small-menu class, for all larger browser windows, the CSS will display the ul list inside the div element with the large-menu class. This creates an effect where the page will shift between menus when the browser window crosses width of 801px. @media screen and ( max-width: 800px ) { .small-menu { display:inline; } .large-menu { display:none; } Responsive Elements and Media 16 } @media screen and ( min-width: 801px ) and ( max-width: 1024px ) { .small-menu { display:none; }. .large-menu { display:inline; } } @media screen and ( min-width: 1025px ) { .small-menu { display:none; } .large-menu { display:inline; } } For the larger screen sizes, you can use the same ul list and use the media query even further to deliver a different menu by simply switching out the CSS and using the same HTML. For the medium-sized menu, use CSS to display the list items as a horizontal list, as shown in the following code snippet: .large-menu ul{ list-style-type:none; } .large-menu ul li { display:inline; } This turns the list into a horizontal list. We want this version of the navigation to appear on the medium-sized browser windows. Place it inside the media query ranging between 801px and 1024px, as shown in the following code snippet: @media screen and ( min-width: 801px ) and (max-width: 1024px ) { .small-menu { display:none; } .large-menu { display:inline; } .large-menu ul { list-style-type:none; } .large-menu ul li { display:inline; } } @media screen and (min-width: 1025px ) { .small-menu { display:none; } Chapter 1 17 .large-menu { display:inline; } } To further utilize the responsive navigation elements in the best way possible, we want the menu list version to move to a different layout location when the screen's width changes. For the middle width, 801px to 1024px, the menu stays on top of the page and has a 100% width. When the screen is wider than 1025px, the menu will float to the left-hand side of its parent element. Add to the 801px to 1024px media query a 100% width to the large-menu class, and to the 1025px media query, add a 20% width and a float:left value to the large-menu class. To fill out the page we will also add a paragraph of text wrapped in a div element. You can go back to the Lorem Ipsum text generator to create filler text ( In the medium-width media query give the element containing the paragraph a 100% width. In the largest media query, give the element containing the paragraph a width of 80% and float it to the right-hand side of its parent element.

Loremipsum dolor sitamet, consecteturadipiscingelit…

Responsive Elements and Media 18 And your style should look as shown in following code snippet: Chapter 1 19 The final result is a page with three different versions of the navigation. Your audience will be amazed when given an optimized version of the menu for each particular browser window size. You can see the navigation elements in all their glory in the following screenshot: How it works… Each version of the navigation utilizes the media query CSS3 property to maximize the space available for the menu and the content. In the smallest window, below 1024px, the navigation is packed neatly inside a select form element. The medium window, ranging from 1025px to 1280px, the navigation is inline and spans across the top of the page, and is followed by the content. Finally, in the widest browser widths, the menu floats on the left-hand side and takes only 20 percent of the horizontal screen space, while the content is maximized on the remaining 80 percent (right-hand side) of the wide-browser window. This technique requires more planning and effort, but is well worth it to deliver the best possible viewing to your audience. Making a responsive padding based on size To complement a responsive width image element, relative padding can be added. With a static width padding, the image padding may appear too thick in smaller browser windows and overcrowd any other elements nearby, or may push the image off the screen. Responsive Elements and Media 20 Getting ready A good place to start is with some understanding of the calculation of the box model properties. The total width an object takes is its actual width plus its padding, border, and margin on both sides, or 2 x (margin + border + padding) + content = total width. How to do it… For an image that is 200px wide in its normal non-responsive state, your typical padding may be 8px, therefore using the previous box model, the formula can be framed as follows: 2 x ( 0 + 0 + 8px ) + 200px = 216px To find the percentage of padding, divide the padding by the total width, 8 / 216 = 0.037% rounded to 4%. We created this CSS and HTML earlier when we created the responsive percent-width image. Add to the image class a padding of 4%.

ipsum dolor sit amet, consecteturadi…

robot image

ipsum dolor sit amet, consecteturadipiscingelit…

To help you see the actual padding width change as you change the browser window's size, add a background color (background-color: #cccccc;) to your image CSS. Chapter 1 21 How it works… The image padding set at 100 percent will stick to the edge of its parent element. As the parent element size changes, the image padding adjusts accordingly. If you have done your box model math properly, your layout will successfully respond to your browser window's changing width. Making a CSS3 button glow for a loading element Your website, like many others, may cater to impatient people. If your site has a submitable form, your users may find themselves clicking the "submit" button a number of times impatiently if your page does not load the new content quick enough. This can be a problem when it causes multiple form submissions with the same data. Getting ready You can stop this behavior by adding some simple visual cues that tell the user something is happening behind the scenes and to be a little patient. If it's a little bit flashy, it might even bring a little sunshine into their otherwise hurried lives. This recipe does not require any images, we are going to create a handsome gradient submit button using CSS only. You may want to pause and go get a cup of coffee, as this is the longest recipe in this chapter. How to do it… You can start by creating a form with some text boxes and a submit button. Then, make the form really cool, use the HTML5 placeholder property for the label. Even with the placeholders, the form is pretty boring. Note that this is not yet supported in Internet Explorer 9.

My Form

Responsive Elements and Media 22 By adding CSS properties we can start giving the button some life: input[type="submit"] { color: white; padding: 5px; width: 68px; height: 28px; border-radius: 5px; border: 1px; font-weight: bold; border: 1px groove #7A7A7A; } This is illustrated in the following screenshot: The button can become even more shiny when we add a CSS3 gradient effect. To accomplish this, there must be a different line of CSS for each browser rendering engine: Opera, Internet Explorer, WebKit (Chrome and Safari), and Firefox. You can add as many gradient shifts as you like, simply by adding a color phase and the % location from the top, each shift separated by a comma, as shown in the following code snippet: This effect is illustrated in the following screenshot: Another effect can be added to the button by CSS, the hover effect. With this property, when the pointer moves over the button, it looks like it is being pressed in. The following CSS will help you add that dark border to the button: input[type="submit"]:hover { border: 2px groove #7A7A7A; } This is displayed in the following screenshot: Responsive Elements and Media 24 Using CSS3 Box Shadows and jQuery we can make a simple animation of a pulsing halo around the Submit button after you pushed it. Create an event listener with jQuery that listens for the button's click event, and on that click event a series of class changes on the form button element. The partial-fade class will be added by the script to the button element. Don't forget to add a link in your head tag to the jQuery source: Then, insert the following script after the form closes: To finish making the button glow when you click it, add the new class partial-fade, to your CSS file and give it a CSS3 Box Shadow Property, and change the border properties. Now, the Submit button will give a flash of blue when pressed. The following screenshot shows the final product: Whew! This button was a lot of work for such a small detail, but the details like this will really help make a great-looking website. This happens to be one of my favorite details to surprise my audience with. How it works… The CSS3 background gradient is an easy way to make a great-looking button consistently across browsers. The gradient is complicated and each browser currently requires its own line for CSS. You can control the gradient breakpoints by adding the percentage and colors manually. Adding box shadow, borders, and jQuery make fun effects on the button when the event is fired. 2 Responsive Typography In this chapter, you will learn about: ff Creating fluid, responsive typography ff Making a text shadow with canvas ff Making an inner and outer shadow with canvas ff Rotating your text with canvas ff Rotating your text with CSS3 ff Making 3D text with CSS3 ff Adding texture to your text with CSS3 text masking ff Styling alternating rows with the nth positional pseudo class ff Adding characters before and after pseudo elements ff Making a button with a relative font size ff Adding a shadow to your font ff Curving a corner with border radius Introduction This chapter deals mostly with how to make responsive typography. You will learn recipes for optimizing your text for various types of device, as well as methods to embellish your typography. The technologies involved are simply CSS3 and HTML5's canvas element with JavaScript. With responsive typography, you can apply a number of exciting effects to your text. When finished with this chapter, you should be armed with a number of techniques that will get you started on the road to making amazing responsive websites. These recipes cover the basics, but when combined together with some creativity, they will enable you to do some fantastic production. Responsive Typography 28 Creating fluid, responsive typography This recipe is a simple example of responsive typography. It will demonstrate the use of the new size unit REM. REM means Root EM. This simply means that the size of the font is relative to the root's font size, not the parent, as with the EM unit. Getting ready Without any further discussion, let's jump into this recipe. Go get some filler text from my favorite Ipsum generator ( Generate at least one paragraph and copy the text into your clipboard. How to do it... Now, paste the filler text into your HTML document and wrap it in a paragraph tag. Give the paragraph element class= "a", then make a copy and assign the new paragraph class="b", as shown in the following code snippet:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

ultricies ut viverra massa rutrum. Nunc pharetra, ipsum ut ullamcorper placerat,

Next, create a style for the base HTML font-size property, and then one for the static sized paragraph to compare the font size changes—similar to an experiment's control group: html{font-size:12px;} p.b{font-size:1rem;} Next create two @media queries, one for orientation:portrait, and the second one for orientation:landscape. In the orientation:portrait media query, style the "a" class paragraph element with a font-size value of 3rem. And in the orientation:landscape media query, style the "a" class paragraph with the font-size value of 1rem. @media screen and (orientation:portrait){ p.a{font-size:3rem;} } @media screen and (orientation:landscape){ p.a{font-size:1rem;} } Chapter 2 29 Now when you resize your browser window from landscape to portrait mode, you will see the font size of the first paragraph goes from a ratio of 1:1 to the base size, to 3:1 of the base size. While this seems very simple, this recipe can be varied and built on to create a number of impressive responsive typography tricks. How it works... When your browser makes a request, the CSS3 @media query returns some conditional styles based on viewport's width. It loads or builds (rebuilds) on the fly for changes to the viewport's size. While not many in your audience are going to spend much time resizing your website in their browser, it is easy to spend too much time worrying about how your website shifts from one size to the next. See also ff The Making a button with a relative font size recipe Making a text shadow with canvas HTML5 brings a new element to web design, the element. This is used to create graphics on a web page on the fly using JavaScript. Getting ready The element creates a rectangular area on your page. It dimensions default to 300px by 150px. You can specify different settings inside the JavaScript. The code in this recipe grows quickly, so you can get the whole code online at the Packt Publishing's website. How to do it... To begin, create a simple HTML page with a element: Responsive Typography 30 The JavaScript gets the canvas element from the DOM. var canvas = document.getElementById('thecanvas'); It then calls the getContext() method. The getContext('2d') method is the built-in HTML5 object. It has a number of methods to draw text, shapes, images, and more. var ctx = canvas.getContext('2d'); Next, start drawing the text within the JavaScript. Here, we create a code to draw the horizontal and vertical shadow offsets, the blur, and the color of the shadow. ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 2; ctx.shadowBlur = 2; ctx.shadowColor = "rgba(0, 0, 0, 0.5)"; The text and its properties is written in the JavaScript here, but can be passed in as a variable from the DOM: ctx.font = "20px Times New Roman"; ctx.fillStyle = "Black"; ctx.fillText("This is the canvas", 5, 30); Back in the HTML, add the onload="drawCanvas();" script command to the body element. When the page loads, the JavaScript fires and draws the text and its shadow onto the canvas. This is illustrated in the following screenshot: Chapter 2 31 How it works… Without getting too deep into the gears of JavaScript, the canvas element provides a place for the designer to script some content directly to the page on page load. The body element's onload="drawCanvas();" command fires the JavaScript, which draws the content onto the canvas. See also ff The Rotate your text with canvas recipe Making an inner and outer shadow with canvas This recipe also uses canvas and JavaScript to draw the text and the effects in your browser. There is no direct method to make an inner-glow or inset-shadow effect using canvas, however, using the stroke method, you can simulate an inner shadow in your text. Getting ready This recipe starts with some already-written code. You can download this from Packt Publishing's website. It is also the same code you created in the recipe, Making a text shadow with canvas. This code should be run on your local computer without any special web server. You can get the whole code online at the book's website. How to do it… To begin, create a simple HTML page with a element. The JavaScript gets the canvas element from the DOM. var canvas = document.getElementById('thecanvas'); Responsive Typography 32 It then calls the getContext() method. The getContext('2d') method is the built-in HTML5 object. It has a number of methods to draw text, shapes, images, and more. var context = canvas.getContext('2d'); This script uses multiple effects combined to make an inner and outer shadow. You add a drop shadow and two different outlines. First, add a drop shadow to the top-left part and make it black with a context.shadowBlur value of 2. Building on that, after context. fillText, add context.strokeStyle and context.strokeText to the canvas context. context.shadowOffsetX = -1; context.shadowOffsetY = -1; context.shadowBlur = 2; context.shadowColor = "#888888"; context.textAlign = "left"; context.font = "33px Times New Roman"; context.fillStyle = "#666"; context.fillText("This is the Canvas", 0, 50); context.strokeStyle = "#555"; context.strokeText("This is the canvas", 2, 50); context.linewidth = 2; Instead of a raised look, the text appears to be beveled in and has an inner glow or shadow effect. The effect is displayed in the following screenshot: Chapter 2 33 How it works… As stated in the beginning of this recipe, there is no true direct method to make an inner shadow in canvas, but there are ways to use the context.fillText and context.strokeStyle methods together that will create something that sufficiently looks like an inner shadow. Rotating your text with canvas The HTML5 canvas methods can do more than just coloring the text or adding drop shadows. You can also use it to move or manipulate the objects in the canvas area. In this recipe, we will rotate the objects in the canvas. Getting ready This recipe builds on top of the previous recipes. If you skipped them, that's okay, you can go back to the previous recipe to refer to the complete code. How to do it… Once you have your previous recipe's canvas set up, the basic steps for rotation are easy. Add a rotate method to the beginning of the function: context.rotate(Math.PI/4,0,0); You will probably notice that the text rotated right off of the canvas. What happened? The rotate method rotates the entire canvas and is not aware of what is in it. The canvas has a small default size of 300px by 150px. Changing the element's size attributes will not affect the canvas size, but distorts the objects drawn on it. To change the size of the canvas and the objects drawn, add the canvas.width and canvas.height properties in the JavaScript: canvas.width=250; canvas.height=250; In addition, because the canvas rotates entirely itself, and not the text rotating about an origin, the text location will need to be repositioned to desired location. In this case, change the object offset of the fill and the stroke: context.fillText("This is the Canvas", 140, 1); context.strokeText("This is the Canvas ", 140, 1); Responsive Typography 34 This is depicted in the following screenshot: How it works… The JavaScript uses the rotate method to rotate the whole canvas element and everything drawn inside it. It requires a small amount of forethought when using the rotate method in the canvas. It is complex, but is the perfect tool to use in large responsive web projects. See also ff The Rotate your text with CSS3 recipe Rotating your text with CSS3 CSS3 provides an easy way to rotate your text. The transform:rotate property is easy to implement and provides a simple solution when the project does not require the complexity of the canvas. Getting ready Write a line of text in your HTML document. Brace yourself; you are about to rotate it with CSS3. Chapter 2 35 How to do it… Wrap the text in a paragraph tag element:

I think, therefore I am

Then, add the CSS transform property to rotate the text. Each browser renders this differently, so each will need its own unique transform property. However, each will use the transform property's subproperty rotate, followed by the degrees of rotation, as shown in the following code snippet:

I think, therefore I am

How it works… The transform property applies a 2D or 3D transformation to an element. Other property changes available are move, skew, and perspective. See also ff The Rotate your text with canvas recipe Responsive Typography 36 Making 3D text with CSS3 In previous recipes, we created a drop shadow, bevel, and an inner shadow, using the canvas element. With CSS3, we can do this to make your text really stand out. Using the CSS3 text-shadow property, we can make your text look as if it is jutting out of the screen towards your viewer. Getting ready If you would like to skip ahead, you can get the code online at Packt Publishing's website. Otherwise, if you are the learning-by-doing type, let's make our 3D text. We create the 3D effect by using a combination of CSS3 shadow effects. How to do it… In your IDE, create a new HTML document with only a header in the body. Add a style section to the head tag and assign the header the property, color:#f0f0f0;, as shown in the following code snippet: Now add to it a series of seven increasing-decreasing X- and Y- positioned text-shadow properties, from 0px 0px0px #666, to -6px -6px 0px #666;. text-shadow: 0px 0px0px #666, -1px -1px 0px #666, -2px -2px 0px #666, -3px -3px 0px #666, -4px -4px 0px #666, -5px -5px 0px #666, -6px -6px 0px #000, Your header now leaps off the screen. Well, almost! To make sure it really pops off the screen, let's give it some more effect. When building any 3D objects on a screen, it is important to give consistent lighting and shadows. Since this text rises above, it needs a shadow. Add another series of six X- and Y- positioned text-shadow properties, only this time give them positive values and a lighter color (color:#ccc;). 1px 1px 5px #ccc, 2px 2px 5px #ccc, 3px 3px 5px #ccc, Chapter 2 37 4px 4px 5px #ccc, 5px 5px5px #ccc, 6px 6px 5px #ccc; The drop shadow makes sense, but it still looks a bit fake, well let's take it to another level; let's blur and darken the elements on the background. The third number in your text-shadow property creates the blur, so add an increasing blur of 0, 0, 1, 1, 2, 3, and 5, as shown in the following code. Also, change the colors to grow darker as you go back: #888, #777, #666, #555, #444, #333, and #000. text-shadow:0px 0px0px #888, -1px -1px 0px #777, -2px -2px 1px #666, -3px -3px 1px #555, -4px -4px 2px #444, -5px -5px 3px #333, -6px -6px 4px #000, Now your header has a truly realistic 3D effect. The effect illustrated in the following screenshot: How it works… Play around and experiment with variations of this recipe for some very exciting typographic effects. CSS3 brings a whole new level of excitement and depth to typographic design that has always been difficult to achieve, and does it well. The text-shadow property can handle numerous shadow properties. Therefore, you can stack them on top of each other in an increasing distance away from your text. This creates the 3D effect on your text. Responsive Typography 38 Adding texture to your text with text masking CSS3 also gives you the awesome power of adding an image mask texture to your text with an image. This effect was previously only achievable by creating a static image of your text with an image-editing software. Getting ready You'll need an image to use as the texture mask. Using an image-editing software, create a new image with an alpha channel. If you do not have an image-editing software that can create a PNG with alpha channels, you can download an open source, free image-editing software GIMP at To create a quick texture effect, use a scatter-type brush to create a textured area near the top of the image. Save it as a PNG image type, preserving the alpha channel, in the images directory of webhost. How to do it… Create your HTML with a header element that will contain the text you want to apply your texture mask to. Then, add some text in it:

I think, therefore I am

Then, add your CSS markup. This will include a large font size (to show off your mask texture!), a white color font, padding and alignment, and then, of course the image mask property. Note that each browser requires its own prefix for the property. h1.masked{ font: 140px "Arial"; color: white; -webkit-mask-image: url(images/mask2.png); -o-mask-image: url(images/mask2.png); -moz-mask-image: url(images/mask2.png); mask-image: url(images/mask2.png); text-shadow: 0px 0px 10px #f0f0f0; width: 100%; padding: 12% 0 12%; margin:0; text-align: center; } Chapter 2 39 The CSS effect is displayed in the following screenshot: How it works… The mask image cuts out the visible portion of the element according to the mask image's alpha. When applied over the text in the CSS, it will cut out the masked portions. This works in a very similar way to the image-editing software's alpha channel layer. Styling alternating rows with the nth positional pseudo class The positional-pseudo classes in CSS3 offers easy CSS solutions to problems that previously required annoyingly complicated solutions. Until very recently, to style alternating rows of a list or table, if you were fortunate enough to be able to work on a server with some sort of logic, you could at least iterate through a count in a list, or if unlucky, you had to manually numerate your rows. Getting ready The CSS3 solution is surprisingly simple. First, create your HTML list of values. This does not necessarily require a name-spaced class, as you might want this to be an universal style throughout your site:
  • I think, therefore I am Responsive Typography 40
  • I think before I act
  • I think I can, I think I can
How to do it… Add a CSS property for the list item,
  • , with the nth positional pseudo-class odd value. Give it a value of a background color and font color that is noticeably different than your default color scheme. ul{ width:100px; } li:nth-of-type(odd){ background-color:#333; color:#f0f0f0; } This will auto magically style the odd numbered rows of your list! The following screenshot illustrates this effect: Now take a breath; that was so easy! Chapter 2 41 How it works… According to, the :nth-of-type(an+b) pseudo-class notation represents an element that has an+b-1 siblings with the same expanded element name before it, in the document tree for any zero or positive integer value of n, and has a parent element. What does that mean? It means that as long as it has similar siblings inside the same parent element, you can either enter in a formula like (-n+2) for the last two rows of the siblings, or keeping it simple, even or odd, and style those rows via CSS. Adding characters before and after pseudo elements In what seems like a lost episode of The Twilight Zone, a new property of CSS gives you the ability to add pseudo markup to your content. As strange as it may sound, there are a surprising number of use cases for this sort of styling. You may want to wrap a section of your content in quotes, and not have to deal with the extra coding trouble to put quotes in your content or theme file, which of course is a sensible thing to do. Or perhaps you want to join in with the popularity of Twitter and its hash-tag and the @ markups, you can precede your content with a # or @ symbol, just by using CSS markup, as shown in the following code line: #I think, therefore I am# Getting ready This requires no server-side logic or fancy footwork of any kind. All you need is to be able to launch the page in your localhost to see it in action. How to do it… This is accomplished with CSS only, therefore all you need to create in your HTML is a class or id property wrapped around the target content:

    I think, therefore I am

    The CSS markup is only a bit complicated, in that the inserted symbol adheres to the margin and padding rules of the content. It uses the nth class:before and class:after pseudo classes. So, the CSS for before is .class:before {content:"#";}. Simply replace # with whatever symbol you want to use. And for after, replace .class:before{} with .class:after{}. .hashtag { border:1px solid #ccc; Responsive Typography 42 display:block; width:200px; height:10px; } .hashtag:before{ content:"#"; } .hashtag:after{ content:"#"; } How it works… The before and after pseudo elements in CSS generates content before or after the element's content. Be careful that they are not real content or elements, and cannot be used for markup or JavaScript event triggers. Making a button with a relative font size There are several use cases for having a responsive button font size. A good example of a use case is for mobile versions of your site. When a regular button is viewed on your iPhone, it is tiny and difficult to press. The last thing we want to do is to create a bad experience for mobile device users through our negligence of mobile devices. Getting ready The goal of this recipe is to use the new font measure of REM to make a responsive button font size that will grow larger when viewed on your mobile device. REM is a new unit introduced in CSS3, it stands for Root EM, or relative to the root font size. This is different from EM, which was relative to the parent. One way to use it is to set the size of certain elements to the base size of the body font. How to do it… It can be used with the @media query to build a responsive button for your desktop and mobile devices. Here's what to do. First, create a simple HTML page with some filler text ( and a input type of submit.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum vehicula enim at dolor ultricies ut viverra massa rutrum. Nunc pharetra, ipsum ut ullamcorper placerat, Chapter 2 43

    Next add CSS for the HTML's base font size at 62.5%, and a static font size for the paragraph, as an experimental control group: html{font-size:62.5%;} p{font-size:1.4rem;} The next step is to create your @media query for the mobile device, and two different desktop window sizes. I'm adding an additional @media query for desktop screens, so if you do not have access to a mobile device you can still see the responsiveness in action. Set up two @media queries for the desktop at 1024px and 1280px and two for mobile devices, both with max-device-width:480px, one with orientation:landscape, and other one with orientation:portrait. @media screen and (min-width:1024px){ } @media screen and (min-width:1280px){ } @media screen and (max-device-width: 480px) and (orientation:landscape){ } @media screen and (max-device-width: 480px) and (orientation:portrait) { } In your desktop @media queries, add an input element to both; and a font-size:1rem value to the min-width:1024px query, and a font-size:2rem value to the min- width:1280px query. To both queries add the properties: width:84px; and padding:2%;. In the mobile @media queries, add the input element to both. In the orientation:landscape media query, assign the properties: font-size:2rem; and width:25%;. And in the orientation:portrait media query, assign the properties: font-size:2.4rem; and width:30%;. @media screen and (min-width:1024px){ input{ font-size:1rem; width:84px; padding:2%;} } @media screen and (min-width:1280px){ input{ font-size:2rem; width:84px; padding:2%; Responsive Typography 44 } } @media screen and (max-device-width: 480px) and (orientation:landscape){ input{ font-size:2rem; width:25%; padding:2%; } } @media screen and (max-device-width: 480px) and (orientation:portrait){ input{ font-size:2.4rem; width:30%; padding:2%; } } Now when you view this page from a mobile device you can see how the REM size unit creates a font, sized relative to the base font. The mobile device may render the font so small it is hardly readable, and the button too small to use without fumbling. Turn the device from portrait orientation to landscape and you will see the button and its font change sizes. Compare the mobile device button to the desktop versions. You will see the button displays unique properties per device type. And, as you drag the desktop browser window between the 1024px and 1280px sizes the button font changes also. How it works… The REM font size unit creates a font size relative to the base font size declared in the HTML or body elements, or if undeclared relative to the built-in base size of the font. The @media query we wrote gives a new relative size for the different devices and orientations. Adding a shadow to your font With CSS3 you can easily add a shadow to your text. This effect can be used to either give a special element a highlighted effect, or used throughout your body text to enhance the look of your content. In addition, you can use it to highlight links within your text to help them stand out. Chapter 2 45 Getting ready CSS3 makes this easy, so there isn't a big setup. Open your development environment, or a Notepad program and get started. You can also go online to Packt Publishing's web page for this book and get the completed code and take a look inside. How to do it… First, create a paragraph element of text; recall that you can get this from our favorite filler text generator, And give the text a title header:

    I think therefore I am

    Lorem ipsum dolor sit amet…

    In your paragraph, insert some links, by wrapping a couple of words in an href tag:

    I think therefore I am

    MorbivenenatisLorem ipsum dolor sit amet… scelerisque Lorem ipsum dolor sit amet…

    First, let's give your paragraph text a drop shadow, this is a simple CSS3 dropshadow effect we can use on the text. Add the property text-shadow in your CSS. For Internet Explorer, add the filter property. text-shadow: 1px 1px 2px #333333; This gives your text a slight shadow that makes it pop off the page. For body text, anything more than a slight shadow will be too much. Foryour links, to make them stand out more, we can add multiple levels of text shadow. Add a shadow similar to the previous example, and then following a comma, add another shadow effect. This example adds a light blue shadow to the link text. text-shadow: 0px 0px 1px blue, 1px 1px 2px #333333; filter: dropshadow(color=blue, offx=1, offy=1); Let's add an old property to give the page some new shine. Let's make your links flash on the pseudo-action hover (:hover): p.shadowa:hover{ text-shadow: 0px 0px 8px #ffff00, 2px 2px 3px #666; filter: dropshadow(color=#ffff00, offx=1, offy=1); } Responsive Typography 46 This property makes the links in the paragraph flash with a yellow glow, when you hover over them. This effect illustrated in the following screenshot: How it works... This recipe is a combination of shadow effects. You can combine multiple shadow effects to create realistic 3D effects for your type. The best way to learn is to experiment until you are extremely satisfied with your 3D effects. Curving a corner with border radius Curved corners were at one time the Holy Grail of the web design world. It was always possible, but never simple. A designer had a limited number of bad choices to employ to make an element have a curved corner. Getting ready This is now achieved without too much fuss with CSS3. The border-radius property is a simple method of creating a rounded corner on an element. How to do it… First create your HTML element. This works on any element that can have a border. So let's make a paragraph block of text. You can get filler text at

    Lorem ipsum dolor sit amet…

    Chapter 2 47 Next add CSS to fill out the paragraph element: .rounded{ background-color:#ccc; width:200px; margin:20px; padding:20px; } Then, to round the corners, add the CSS3 property, border-radius. In this example, I used a curve radius of 5px. border-radius: 5px; -webkit-background-clip: padding-box; background-clip: padding-box; This property gives you simple and easy-rounded corners. This is great for a floating element on a page. But what if you wanted to round only the top corners for a menu element? Still easy. Let's start with a simple inline list: Next add the CSS to make the list inline, with padding and margins: li.rounded-top{ display:inline; background-color:#ccc; margin:3px; padding:8px; } The CSS in the previous example gives you rounded corners for all the corners. To have different rounded corners, specify a radius for each corner. border-radius: 8px 8px 1px 1px; You can achieve the same results by specifying each corner as its own CSS property: border-top-left-radius:8px; border-top-right-radius:8px; border-bottom-right-radius:2px; border-bottom-left-radius:2px; Responsive Typography 48 You can take this further by adding another level of curved radius: border-top-left-radius:8px 4px; border-top-right-radius:8px 4px; border-bottom-right-radius:2px; border-bottom-left-radius:2px; The new look is shown in the following screenshot: To add another level of responsiveness try replacing the curved radius entries with percentages. Go back to the first example in this recipe and change the CSS to have a percent radius curve: border-radius: 1%; How it works… The border-radius property provides a simple rendering of a curve on an element. This property takes four values, but can be written in the shorthand format with only one curve radius. 3 Responsive Layout In this chapter, you will learn about: ff Responsive layout with the min-width and max-width properties ff Controlling your layout with relative padding ff Adding a media query to your CSS ff Creating a responsive width layout with media queries ff Changing image sizes with media queries ff Hiding an element with media queries ff Making a smoothly transitioning responsive layout Introduction This chapter has some challenging recipes. Responsive layouts often present some difficult challenges that can push you to create a great solution. With responsive design methods you can do much more, and do it more efficiently. Responsive layouts have introduced a whole new area of challenges to web development and a new dimension of excitement. Responsive layout with the min-width and max-width properties Many responsive layout techniques can be quite complex and overwhelming, but in this recipe you will see a fairly simple layout using the min-width and max-width properties applied to three floating elements. With this very simple responsive layout feature of CSS, you are ready to display your site on mobile devices and desktop screens of various sizes. Responsive Layout 50 Getting ready Floating elements that collapse from multiple columns into one column on a small viewport is not a new trick. This has been around for years as a standard property of CSS1, however, there was never any reason to consider it useful until the mobile devices became common. So let's combine this old, stale property with some other fresh CSS properties to make a responsive layout. How to do it… Create a simple HTML page enclosed in an article element, containing a h1 header and three elements. The first element will contain an image and the second and third will contain filler text. Assign to all of the inner elements a class of float and respectively one, two, and three as their IDs:

    Responsive Layout with min and max width

    Pellentesqueeleifendfacilisisodio ac ullamcorper. Nullamutenimutmassatinciduntluctus...
    Pellentesqueeleifendfacilisisodio ac ullamcorper. Nullamutenimutmassatinciduntluctus. Utnullalibero, …
    Next, create your style for the .article element and assign the properties: width: 100%;, max-width: 1280px;, and auto side margins. Then, center the h1 title. Assign the img element the width: 100% and height: auto; properties to make it responsive to its parent element. For the floating element containing the img element, give it a min-width value of 500px. You could also give each floating element a different background color to make them more discernible, but this is not vital to the layout. To all the floating elements in the .float class, add a max-width: 350px property, left float, and for clean looks, justify the text. Once everything is put together and you have the HTML document open in your browser, you will see how the layout smoothly goes from a three-column layout to a two-column layout, and then finally to a single-column layout, as shown in the following screenshot: Responsive Layout 52 How it works… The max-width property of the columns allows them to have a fluid but a maximum width. This gives you more flexibility in the layout of the columns than you would have with a static width. The image column utilizes the min-width property so it can respond to parent element width's changes by growing and shrinking. Finally, the whole layout can smoothly break down from three columns to one column by using the float property; once there is not enough room for the elements to float side by side, the last element drops to a new row. Controlling your layout with relative padding Let's put together a simple layout for a blog with comments and comment replies. This is possible using only relative padding for the layout. You say, "That's crazy! How can you control a page layout with nothing but padding?" Let's find out. Getting ready Of course, a blog is much more dynamic than a static HTML page, so this would be a good part of a comments template section for your favorite blogging software. That being said, this recipe is remarkably easy, and yet effective. So, go get yourself some Ipsum filler text and get ready to troll yourself. How to do it… The first step is to create a very simple blog style page with comments embedded in the div element. In your HTML body, create the element that will hold everything, the .content div. Give it a h1 title, a paragraph of Ipsum filler text, and follow it with a .comments element. Inside the .comments element you will build your embedded comments layout.
    Control your layout with relative padding

    Pellent esque eleifend facilis isodio ac ullam corper. Null amuten imut massat incident luctus. Utnull alibero, el eifend vel ultrices at, volut patquis quam...


    No 2 x h1
    Chapter 3 53 Under the .comments title, you will add your first comment. And next, inside that comment, immediately after the closing paragraph tag add a comment to that comment: Continuing from there, you can insert more comments the same way to a comment on the parent comment, or add a comment outside of the parent div element to make the comment to the parents' parent, all the way up to the original blog post:
  • Eventually, you can have many comments and a good looking working layout built simply with only relative padding. The CSS to make this work is surprisingly easy. Simply add the classes: .content, .comments, and .comment. In the content class add some side padding, and in the comment add heavier padding to the left. .content {padding:0 5% 0 5%;} aside {padding:0 10% 0 20%} .comment {padding:0 0 0 10%} This is illustrated in the following screenshot: Chapter 3 55 How it works… The relative padding attribute responds to page width changes by adjusting its own width. Adding a media query to your CSS In this recipe, we will explore the awesome power of the media query by rendering a simple web page with every permutation and device available in the universe. Okay, I'm exaggerating a little, I admit. But we will create a simple web page that will respond to several browser window sizes, devices, and other possible presentation methods. Getting ready Solely for the purpose of this recipe, go out and purchase one of each of the devices and variations described here. You'll need a new high definition TV, a smart phone, a not-so-smart phone, and at least one printer. No way? Okay, but I'm just trying to help you and the economy. That being said, of course it will be impossible to truly test every media query, but do what you can. There are a surprising number of possibilities. But in most real-life scenarios, you are unlikely to need or care to use most of these. We will at least try to cover the most commonly used media queries. I will skip over those that I think are unnecessary to you. You can easily access information about these if you find yourself in a project with requirements to create presentations for one of these obscure devices. You never know! The WC3 has all of the detailed information and descriptions of these if you need them at I will exclude the examples and just for your reference include numerous devices with specific color limitations, including monochrome, print, TV, and handheld. The media queries you will need most likely are screen and print. How to do it… Create a simple HTML page with a h1 title, and an element wrapping around an image, and a paragraph of text. Get some Ipsum filler text if you don't have any text lying around. It will look just like the following:

    Add Media Query to your CSS

    Pellent esque el eifend facilisis odio ac ullam corper. Nullam ut enim ut massa tincidunt luctus…
    Responsive Layout 56 Next create a series of media queries. In the following list, I will give a brief explanation of what each does: @media print{...} This is applied to the web page when it's printed. You can test this by selecting File | Print and then view the print preview. This is useful for web pages where users will be printing it as a document to read. You can take advantage of this and change or remove the formatting to make this version as simple as possible. @media (orientation: portrait){...} This is generally applied on any device that shows the document in portrait mode. You can use it for mobile devices to change the look for different orientations. Be cautious because this also will be applied to desktop screens unless you specify it to smaller screens or devices only. The media query orientation's other possible value is landscape. @media (height:500px){...} The height and width media query allows you to specify style for specific screen dimensions. @media (device-width:500px){...} This media query will apply a style to any page, regardless of browser's window size, that is viewed on a device of the specified dimensions. @media screen and (device-aspect-ratio: 16/9) {...} This media query can be used to define styles for screens (not print) with a view window of the 16/9 ratio. @media tv {...} This aspect ratio would apply only to a device using a television to view. @media screen and (max-width:960px){...} @media screen and (min-width:961px) and (max-width:1280px){...} @media screen and (min-width:1281px) and (max-width:1336px){...} @media screen and (min-width:1336px){...} The min-width and max-width media queries are the most useful one. Here, you can define a responsive style for any window size including the small-screen mobile devices. I typically start by defining the smallest—or mobiles—viewports breakpoint, and define their styles, and then create breakpoint ranges for the most popular screen sizes, ending with a min-width media query to apply to the largest screen sizes. Chapter 3 57 Once you have created the media queries that you think are useful for your current project, add styles to the media queries with different values: @media tv { body {color: blue;} h1 { font-weight: bold; font-size: 140%; } img { float: left; width: 20%; border: 2px solid #ccc; padding: 2%; margin: 2%; } p { width: 62%; float: right; font-size: 110%; padding: 2%; } } @media screen and (max-width: 960px) { body {color: #000;} h1 { font-weight: bold; font-size: 120%; } img { float: right; width: 20%; border: 2px solid #ccc; padding: 1%; margin: 1%; } P { width: 80%; float: left; font-size: 60%; } } Responsive Layout 58 @media screen and (min-width:961px) and (max-width:1280px) { body {color: #000000;} h1 { font-weight: bold; font-size: 120%; } img { float: right; width: 20%; border: 2px solid #ccc; padding: 1%; margin: 1%; } P { width: 76%; float: left; font-size: 60%; } } @media screen and (min-width: 1281px) { body {color: #000000;} h1 { font-weight: bold; font-size: 120%; } img { float: right; width: 20%; border: 2px solid #ccc; padding: 1%; margin: 1%; } P { width: 70%; float: left; font-size: 100%; } } Chapter 3 59 The final version of the page is displayed in the following screenshot: How it works… Apply these styles and you will find that a different style is applied to different devices. You can combine a number of these in a clever way to create magic responsiveness in your site. Creating a responsive width layout with media queries In this recipe we will make a simple responsive width layout that adjusts itself to various screen widths. This layout would be a good starter template for a personal blog or news magazine, where you would want your readers to comment on your content and on each other's comments. It may even be a great theme starter to attract trolls to a flame war. This paragraph just sounds silly, sorry! Getting ready This template will work great in a dynamic CMS or blog software, but might not make much sense as a plain HTML page. But most themes work in the same as HTML as far as presentation goes. In most cases, you would simply replace the text and static navigation with template tags. This recipe will need some filler text to demonstrate. If you do not already have some text to work with, go to our old standby Ipsum generator to get some filler text. Responsive Layout 60 How to do it… To begin, create a simple web page, and in the style element create your media queries. You can always link to an external stylesheet, but for the sake of simplicity, this and most of the recipes contain the CSS in the section of your header. Include these standard breakpoints at screen sizes: 960, 1024, and 1280. The first media query affects all viewports narrower than 960px. The second from 961px to 1024px, the third from 1025px to 1280px, and the last affects, all screen sizes larger than 1281px. Within each media query, you will write a CSS for a different layout. There will be some layout CSS outside of the media query along with your style presentation, but most of them will be defined in the media queries. The next step is to create your HTML layout. The basic structure starts with these basic div elements—nav, content, and comments:
    Next add some filler content to your page. This will aid in the demonstration of the layout. In the nav element, add an unordered list with sample menu links. This will serve as a responsive menu. At the pages' narrowest width, the menu will display vertically. In widths ranging from 961px to 1280px, the menu is displayed inline horizontally on top. For larger widths, we want the menu to return to a vertical display and return to the left-hand side. In the first two media queries, the content and comments elements will float left, but with different width ratios. In 960px, these elements should have a width of 90%. In the larger widths, set the content and comments elements at 60% and 20%, respectively. @media screen and (max-width: 960px) { .content {width: 90%;} .comments {width: 90%;} } Chapter 3 61 @media screen and (min-width: 961px) and (max-width: 1280px) { .nav ul li {display: inline-block;} .content {width: 60%;} .comments {width: 20%;} @media screen and (min-width: 1281px) { .content {width: 60%;} .comments {width: 20%;} } To make the menu slide back to the left on the large screens, we will use positioning to create a three column layout. In the min-width:1281px media query, add the .nav element and styles for absolute positioning and width: .nav{ position: absolute; top: 20px; left: 0px; width:144px; } That's almost all the steps necessary to build a responsive layout. To tidy things up, let's add some padding to the layouts. Add the .nav, .content, and .comments elements to the other media queries, and then add padding to those. Refer to the following CSS. The min- width:1281px media query will not have a padding for the .nav element, and the padding for the .content and .comments elements are reduced to allow for the vertical menu. @media screen and (max-width: 960px){ .nav {padding: 1% 5%;} .content,.comments {padding: 1% 5%;} .content {width: 90%;} } @media screen and (min-width: 961px) and (max-width: 1280px){ .nav {padding: 1% 5%;} .nav ul li {display: inline;} .content,.comments {padding: 1% 5%;} .content {width: 60%;} } @media screen and (min-width: 1281px){ .nav { position: absolute; top: 20px; left: 0px; width: 144px; } Responsive Layout 62 .content,.comments {padding: 1% 1% 1% 0;} .content{ width: 60%; margin-left: 144px; } } You can also style the inline menu however you want. For now let's simply add some margins to the li elements. Add this element and styles outside of the media queries, .nav ul li{margin: 2px 10px;}. Finally, on to the content and comments, paste your filler text inside the .content element. I also added the header and paragraph tags inside. We will do something similar for the comments. Remember that we want to allow for embedded comments, or people to comment on comments. There will be a possible inherited hierarchy of comments, and we still need this to look good in all browser sizes, so we should add some padding. Adding a static padding to the .comment element will not look good in all browser sizes. Instead, add a relative padding to each media query's .comments element, so that they take less space as the browser window gets smaller: 90% for the max-width:960px media query and 20% for all larger sizes. Add outside of the media queries, padding-left: 8% to the .comment element, and float the .content and .comments elements to the left. You can also text-align:justify them to make the text look like a block. @media screen and (max-width: 960px) { .nav {padding: 1% 5%;} .content,.comments {padding: 1% 5%;} .content {width: 90%;} .comments {width: 90%;} } @media screen and (min-width: 961px) and (max-width: 1280px) { .nav {padding: 1% 5%;} .nav ul li {display: inline;} .content,.comments {padding: 1% 5%;} .content {width: 60%;} .comments {width: 20%;} } @media screen and (min-width: 1281px) { .nav { position: absolute; top: 20px; left: 0; width: 144px; } Chapter 3 63 .content,.comments {padding:1% 1% 1% 0} .content { width: 60%; margin-left: 144px; } .comments { width: 20%;} } .content,.comments { float: left; text-align: justify; } .nav ul li {margin: 2px 10px;} .comment {padding-left: 8%;} This CSS will make the padding on comments and embedded comments adjust to the changes in the browser window sizes. As a result, the comments section of your page will show the comment parent-and-child hierarchy, as well as a consistent and workable layout for each browser window size. You can see the code in action demonstrated in the following screenshot: How it works… In this responsive layout we used a few different techniques. First, the media query offers us limited but useful logic to deploy different layout techniques for different browser window sizes. Second, the fluid and floating elements with size ratios adjust with ease to the new layouts. And last but not least, fluid's percent-based padding gives a consistent ratio of padding to the screen size and layout. Responsive Layout 64 Changing image sizes with media queries In this recipe, you will learn how to resize an image with a CSS media query. This can be useful in a number of situations, especially those where you want to download only one image and use it in different size versions in your responsive layout. Getting ready This is a good method for size variation that can be handled on the client side, but be careful not to abuse this method by causing the client to download a really large image file and do heavy resizing in their browser. There are better ways to do that, which were discussed in Chapter 1, Responsive Elements and Media. How to do it… I recommend putting together a small HTML page with a h1 title, the wrap element, and inside wrap, an image and a paragraph of text. You really don't need all of this extra stuff to make an image size change in an image query, however, it will help you demonstrate the use of changing an image size in the media query. Next, create your media queries for the most frequent browser window size breakpoints: 960px, 1024px, 1280px, 1366px, 1440px, and last but not least 1680px. In each of these media queries, add your styles for the elements. In my example, I created media queries at 960px and 1280px: @media screen and (max-width: 960px){ .wrap {padding:0 5%; width: 90%;} .wrap img { width: 90%; height: auto; padding:5%; } .wrap p { width: 90%; padding: 5%; text-align: justify; } } @media screen and (min-width: 961px) and (max-width: 1280px) { .wrap { padding: 0 5%; width: 90%; } .wrap img { width: 50%; Chapter 3 65 height: auto; max-width: 600px; float: right; } .wrap p { width: 50%; text-align: justify; float: left; } } @media screen and (min-width:1281px) { .wrap { padding: 0 5%; width: 90%; } .wrap img { width: 40%; height: auto; max-width: 500px; float: left; } .wrap p { width: 60%; text-align: justify; float: right; } } Now as you resize your page you can see how the image resizes as the browser resizes through the various media queries. This is illustrated in the following screenshot: Responsive Layout 66 How it works… The different media queries, when called by the browser, present different sizes for the element's width and height property. This allows you to optimize your image size for different devices. Use your judgment, and if the original image is too large, look into some server-side resizing as an alternate method. Hiding an element with media queries This recipe will show you some very useful tricks with media queries to make elements disappear off the screen, depending on the browser window's size. There are a few different methods of hiding an element on the screen, I will go through three of them in this recipe. Getting ready This method can have a number of use cases. One very helpful case is using it to switch out menus on the fly when scaling a page down to a smaller device. You could also use this to change the way your content areas or aside contents are displayed. The possibilities are unlimited when you get creative with the methods. How to do it… Set up a simple page for demonstration. In my example, I wrote up a page with a h1 header, an image, and then two elements with text inside them. Next, add some style to those elements. I added a different background color and width properties to each element, mostly, so that I could keep them apart when they disappeared. And then add your media queries at a breakpoint. In the example, I'll add a breakpoint at 960px. And inside the media queries, we're going to take a look at some different methods of getting the element to disappear. In your first media query, max-width: 960px, add the position: absolute and left: 5000px properties for the img element; This style will move the element far enough to the left of the screen that it has for all practical purposes, disappeared. Add to that media query a display: none style to the .bar element. This leaves the element where it is, but renders it invisible. Both of these elements are are effectively gone from the page, leaving only the title and .foo elements. In the second media query, you will try a different way to remove an element from the screen. First, add the .foo element to the media query and give it a left margin of 5000px. That removes it from the screen, however, the next element clears its vertical space and leaves an obvious white space where the element was. Then, float the element to the left and the white space will disappear. This is illustrated in the following code snippet: Chapter 3 67 .foo { background-color: #ccc; width: 300px; } .bar { background-color: blue; width: 600px; color: white; } @media screen and (max-width: 960px) { img { position: absolute; left: 5000px; } .bar {display: none;} } @media screen and (min-width: 961px) { .foo { float: left; margin-left: -5000px; } } Congratulations! Open the project in your browser and see if it looks like the following screenshot: Responsive Layout 68 How it works… Both the absolute position and float do not have a height property, so once applied to an element, they will not occupy any vertical space. This can be an especially useful trick to move elements around on your page. It can also cause some problems when you use floating elements for layout. This behavior can be fixed by inserting a break with a clear:both property after the element. Making a smoothly transitioning responsive layout In this recipe I will guide you through the creation of a multi-zoned and responsive front page. This one will have a number of elements that are responsive in different ways; giving a rich user experience that delivers an impressive layout. I developed this for a startup I was working on and found that I liked it so much that I continued to develop it further to share with you in this recipe. Getting ready This recipe will be a good template for a homepage to a content-heavy site. If you have been building content for a while, this will be perfect for the landing page, and can be modified for a single-item content page easily. If you are just getting started with your site, you can go get some generated text at like I did for this recipe. How to do it... This site breaks down into three HTML elements or a footer, and two elements that sometimes are vertical and sometimes are left and right floats—depending on the screen width. These elements themselves are also divided into smaller elements. So, get started and create a basic page with a top-wrap element, a middle-wrap element, and a footer:
    Next, we start the CSS for these items. Add some basic CSS and the following media queries: body{ margin: 0; padding: 0; } Chapter 3 69 footer {width: 100%;} .clear {clear: both;} @media screen and (max-width: 1280px) { header, .content {width: 100%;} } @media screen and (min-width: 1281px) { header { float: left; width: 60%; } .content { float: right; width: 40%; } } In this basic layout, the header and .content rows both occupy 100% of the page width, while the page is under 1280px. When the page is larger, they occupy the respective 60%/40% split and the float left and right. Next let's build the menus. This menu will employ a responsive trick of using a media query to hide and show two different menus. Essentially, we will build two different menus, and then use CSS to display the optimized one for each screen. The smallest version will use a multi-select drop-down menu, while the larger menu contains two inline lists. Here's what the HTML looks like inside the top-wrap element:
    Add the following CSS for the header elements: nav .small-menu img{ width:9%; height:auto; float:left; padding:0 2%; } nav .small-menu select { margin: 3%; width: 80%; } This will display two different versions of the menu until we add to our media queries. Add media queries to switch between displaying the drop-down menu on small browser windows and the larger inline list menu on larger browser window sizes. Use the display property to show and hide the menus. @media screen and (max-width: 600px) { nav .small-menu {display: inline;} nav .large-menu {display: none;} } Chapter 3 71 @media screen and (min-width: 601px) { nav .small-menu {display: none;} nav .large-menu {display: inline;} } Under the menus, before the closing tag create a space for a large high-quality photo to display on the site. And to prevent it from becoming a wasted space let's put a search box right in the middle of it. We can actually make this search form stick closely to the center of the picture and responsively adjust to screen size changes. This is illustrated in the following simple code: And of course the magic is in the CSS. Let's use some tricks to make the search form hover in the same spot. First give the outer div element a width of 100%, then the search element will get an absolute position and few different properties under different media queries. This combination will keep the search form floating above the middle of the img area. Keep in mind that we are adding new CSS to the media queries. The following CSS code reflects only the additions, not what was already there. It gets rather long if I show the entire CSS expanding each time. At the end, I will include the entire CSS as it should be in its final state. .img-search {width: 100%;} .search {position: absolute; } .top-menu { height: 33px; background-color: #ccc; } .logo img {height: 87px; float: left;} .top-menu nav li {display: inline-block;} .large-menu ul {margin: 0 5px;} .large-menu li {display: inline;} @media screen and (max-width: 600px) { .search { margin-top: 87px; left: 22%;} } Responsive Layout 72 @media screen and (min-width: 601px) and (max-width: 1280px) { .search { margin-top: 144px; left: 40%; } } @media screen and (min-width: 1281px) { .search { margin-top: 144px; left: 22%; } } The .img-search image element will receive a dynamic width of 100%, and auto height. And that's it for the large image search field. Give the next element, .flip-tab, a width of 100%, and any height or other properties you want. You won't have to worry about this again:

    Look Down Here

    .flip-tab {width: 100%; height: 54px; text-align: center;} The next element, .teasers, will get a max-width: 1280px property so it will auto- magically be at 100% width of its parent element, top-wrap, limited to 1280px. This element is simply a container for the three left-floating .teaser elements. These .teaser elements will have two different property sets under different media queries for a 600px breakpoint.

    The First Law of Robotics

    Lorem ipsum dolor sit amet,..

    The First Law of Robotics

    Lorem ipsum dolor sit amet,..

    The First Law of Robotics

    Chapter 3 73 Lorem ipsum dolor sit amet,..

    .teasers {max-width: 1280px;} .teaser {float: left;} @media screen and (max-width: 600px) { .teaser {width: 100%;} } @media screen and (min-width: 601px) { .teaser { width: 32%; min-width: 144px; } } That concludes everything you will be doing in the header element. Up next is the content element, which wraps the content that will float in the right-hand side columns. What's inside this element is nothing more than a two-column float split at a 60/40 ratio, or if the parent element is narrow, each is 100% wide. The content element will have two different property sets under media queries with a breakpoint at 1280px. These elements have some limited sample content. You can add much more once you deploy the layout:
    Find a Robot

    Search or Like Us Locally


    Loremipsumdolor sitamet, consecteturadipiscingelit. Nunc non felisutmetusvestibulumcondimentumuteueros.Nam id ipsumnibh. Praesent sit ametvelit...

    This CSS is more complicated, but remember, you can access this entire work online. As you can see, the elements do zig and zag around a bit, but each breakpoint will have an optimized display. .contact-us {float: left;} .cities {float: left;} @media screen and (max-width: 600px) { .contact-us {width: 100%;} .cities {width: 100%;} } @media screen and (min-width: 601px) and (max-width: 1280px) { .contact-us {width: 40%;} .cities {width: 60%;} } @media screen and (min-width: 1281px) and (max-width: 1366px) { .contact-us {width: 100%;} .cities {width: 100%;} } @media screen and (min-width: 1367px) { .contact-us {width: 40%;} .cities {width: 60%;} } Finally, the footer! (The end of the page!) The footer breaks down into a 100% wide outer
    , and then a footer-wrap wrap with a 100% width, max-width of 1280px, dynamic side margins, and inline-block display. Inside are three elements that always have the property display:inline-block. When the display is small, these elements are each 100% wide, otherwise they are 33% wide, left-floating, with a minimum width of 144px: .footer-wrap{ width: 100%; max-width: 1280px; margin :0 10%; display: inline-block; } .footer-third {display: inline-block;} @media screen and (max-width: 600px) { .footer-third {width :100%;} } @media screen and (min-width: 601px{ .footer-third { float: left; width: 33%; min-width: 144px; } } Responsive Layout 76 As I promised previously, here is the full CSS code: body{margin:0;padding:0;} .img-search {width: 100%} .search {position:absolute;} nav .small-menu img{width:9%;height:auto;float:left;padding:0 2%;} nav .small-menu select {margin: 3%; width: 80%;} .main-img {width: 100%; height: auto;} .top-menu {height: 33px; background-color: #ccc;} .top-menu nav li {display: inline-block;} .logo img {height: 87px; float: left;} .large-menu ul {margin: 0 5px;} .large-menu li {display: inline;} .flip-tab {width: 100%; height: 54px; text-align: center;} .teasers {max-width: 1280px;} .teaser {float:left;} .contact-us {float:left;} .cities {float:left;} footer {width:100%} .footer-wrap {width: 100%; max-width: 1280px; margin: 0 10%; display: inline-block;} .footer-third {display:inline-block;} @media screen and (max-width: 600px) { nav .small-menu {display: inline} nav .large-menu {display: none} .search {margin-top: 87px; left: 22%;} .teaser {width: 100%} .contact-us {width: 100%;} .cities {width: 100%} .footer-third {width: 100%} } @media screen and (min-width: 601px) and (max-width: 1280px){ .search {margin-top: 144px; left: 40%} .contact-us {width: 40%;} .cities {width: 60%} } Chapter 3 77 @media screen and (min-width: 601px) { nav .small-menu{display: none} nav .large-menu{display: inline} .teaser {width: 32%; min-width: 144px;} .footer-third {float: left; width: 33%; min-width: 144px;} } @media screen and (max-width: 1280px) { header, .content {width: 100%;} } @media screen and (min-width: 1281px) { header {float: left; width: 60%;} .content {float: right; width: 40%;} .search {margin-top: 144px; left:22%;} } @media screen and (min-width: 1281px) and (max-width: 1366px){ .contact-us {width: 100%} .cities {width:100%} } @media screen and (min-width: 1367px) { .contact-us {width: 40%} .cities {width: 60%} } This one was long and difficult; thanks for hanging in there! The effect is illustrated in the following screenshot, compare this with your output: Responsive Layout 78 How it works... These CSS and media queries, when combined together, make a responsive footer that can stay centered through all the screen sizes, and collapse down for small mobile-sized browser windows. Responsive layout is an exciting new area of web development methodology. The responsive methodology allows the designer and developer to create for multiple devices, especially mobile devices, without the expense of developing native apps. Very soon, if not already, you can expect many companies to want to take a responsive approach to their site redesigns. There's more... You created a very simple method of responsive almost completely using CSS. I would challenge you to take this one step further by eliminating the dual menus in the nav element. Look in the Adding JavaScript for mobile browsers only recipe, in Chapter 5, Making Mobile-first Web Applications, to add a jQuery method to replace the large menus with the form elements button and submit, and an href pseudo button. Put one of each inside your content
    element. Link button Chapter 5 131 Launch your new page. You will see four new buttons that look identical (with the exception of the text). You can see that each of these methods is delivered the same way. This is impressive, as your non-mobile version of the template file may require you to use a certain type of submit element (which is not exactly mobile-first, but no one is perfect). See the following screenshot: Let's continue with this recipe now by demonstrating how to add icons to the buttons using jQuery Mobile. This is a simple, one-step process; it uses an HTML5 data attribute, the data- icon attribute. In your first button, add the data-icon="delete" attribute; in the next one, add the data-icon="check" attribute; add data-icon="plus" to the next one; and finally, add data-icon="arrow-l" to the last button in this set of buttons. There is a list of icons that you can put in there; you can find them in the documentation. Link button Making Mobile-first Web Applications 132 The following screenshot shows the new buttons: You can also make a button smaller by adding the data-mini="true" attribute and position the icon at the right, left, top, or bottom corners of the button using the data- iconpos attribute. Otherwise, you can use the data-iconpos="notext" attribute to only show the icon. See the following screenshot: Chapter 5 133 The default behavior for these jQuery Mobile buttons is to stretch across the whole screen. You can change this by adding the attribute data-inline="true". Link button It's messy, but you can see it in action here: They will become inline elements, similar to the list items that are displayed as inline. We're almost done, but there's still some fun to be had. We can also make button groups easily. Remove the data-inline="true" attribute that you added in the previous section. Next, wrap the button elements with a
    element, with the attribute data-role="controlgroup".
    Making Mobile-first Web Applications 134 Link button
    Now you can see the potential for creative button groups and keeping them together in a pretty package. Let's add some more effects to the button group. If you add data- type="horizontal" to the "controlgroup"
    element, you'll make a mess that you'll need to clean up. One way to clean this up would be to change all of the data-iconpos attributes to "notext". Finally, as we have seen in the previous jQuery Mobile recipes, the data-theme attribute can make your buttons colorful. To quickly show this effect, add a different data-theme attribute (a, b, c, e) to each of the buttons (I skipped d, it looked too much like c). These are illustrated in the next screenshot: How it works... All you really need to know about how this works is which data tags to use to make jQuery Mobile pick up the HTML elements and turn them into mobile-native buttons. It happens auto-magically actually, when you have the correct attributes, and it works no matter what method of the submit button it is applied to. jQuery Mobile fires an event on the HTML5 attributes and adds the HTML and styles to the rendered page. Chapter 5 135 Adding a mobile stylesheet for mobile browsers only using the media query In this recipe, we want to be able to use a stylesheet in the template only for use by mobile browsers. JavaScript aside, there is no way in client-side rendering to listen for the user agent and deliver some logic or special template for mobile browsers. Let's take the K.I.S.S. approach and get as close as we can with a media query. Of course, there are numerous ways to write JavaScript to detect a user agent, and we will cover that in a later recipe, but for now let's write a killer media query to lock down the mobile browser for a specific CSS. In the previous recipes, our media queries were performed inside a stylesheet. This one will be different as we will put it inside the HTML header link. Change is good, do not worry. The reason we are putting the media query within the HTML link to the CSS file is that we want to call that CSS file only under special circumstances. This recipe is especially useful when you are using mobile-first design and technologies like jQuery Mobile. Getting ready Fire up your handy IDE and start a new HTML page. Be sure to add your viewport tag. If you like, you can add a paragraph of text in the HTML body. How to do it... In the tag of your new HTML file, add two paragraphs of text. Each with a different class (class="a" and class="b"). This will be enough HTML to demonstrate the media query at work.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit.

    Nulla ante tortor, rutrum eu sollicitudin eget, vehicula quis sem. Nullam cursus placerat luctus.

    Now back to the tag. First, let's add the viewport tag. Include the content attribute "width=device-width". Next, add some simple style for the font (font-size: 100%). Making Mobile-first Web Applications 136 Next we're going to add the link to the mobile CSS stylesheet with a media query. The basic stylesheet link contains rel="stylesheet" and the path. Add to it the conditions it needs to satisfy to use that stylesheet. Add a media query for screen and max-device- width=320px. Your CSS link should look like this: There's nothing more for us to do in the HTML file, so create a CSS file in the same directory and name it mobile.css. Open it to edit it. We don't need to do much here, only one line is sufficient. Add a line for the b class paragraph and give it an attribute of 2rem for the font size. REM means Relative EM, or relative to the root font size (in case you skipped the responsive typography recipes). p.b{font-size:2rem} Now let's try it out. Open your HTML file in a browser, and then open it in your mobile device simulator. Here, you can see the mobile device has a unique presentation with a different font size for the b class paragraph. See this recipe illustrated in the following screenshot: How it works... The media query is designed to become active only on devices that have a screen resolution of 320px or lesser. Anything greater than that ignores (it still does get downloaded) the CSS file linked. You could additionally write media queries for other specific devices as well. Chapter 5 137 Adding JavaScript for mobile browsers only In the previous recipe, we wrote a media query inside a stylesheet link. This was useful for our own mobile-first responsive web development. However, when using JavaScript code specifically for mobile platforms, such as jQuery Mobile, you might not want to have them initiated on desktop computers. Let's build a tiny JavaScript code that detects the mobile device screen size and then deploys jQuery Mobile for it but not for the desktop. Getting ready Mobile-first technologies like jQuery Mobile are amazing tools when you have a server-side technology. They do need server-side logic to work the best. If you are not fortunate enough to have access to server-side logic, you can employ some client-side tricks to work your magic. How to do it... If you have not looked through the jQuery Mobile recipes, take a look now; we're going to reuse one of the recipes that we have used already. Open up one of the files that you created in the previous recipe using jQuery Mobile. You can use the Adding a mobile, native-looking button with jQuery Mobile recipe. If you worked through this recipe on making a mobile, native-looking button, use it to follow along. When we last saw this file, the jQuery Mobile script took your plain old boring HTML buttons and turned them into cool jQuery Mobile buttons. All you needed was to include the HTML5 data attributes in your elements, and jQuery Mobile did the rest auto-magically. So what if you only want this to happen on a mobile device? Well, you would be in trouble if it weren't for the magic of client-side scripting. We first want the script to be aware that it is dealing with a mobile device. One way is by querying the user agent of the DOM element. I've seen a few people do that, but it's complicated enough to be bug-prone. So instead, let's detect the size of the device screen. Most mobile viewports are at most 600 pixels wide or smaller; so for now, you are safe if you are developing applications assuming that that is the correct maximum size. So let's make the script get the screen width from the DOM; if it's smaller than 600px, go get jQuery Mobile script. First, using jQuery, fire a function when the document loads. $(document).ready(function(){ // }); Making Mobile-first Web Applications 138 Inside the function, write a conditional statement; if the screen is smaller than 600, then do something. $(document).ready(function(){ if (window.screen.width < 600){ //Do something! }; }); That's a good start, but let's be more specific about "doing something". What we want the script to do is fetch and run the jQuery Mobile script. A good method for that is jQuery's $.getScript() function. So put that in the if condition, including the jQuery Mobile source URL. $(document).ready(function(){ if (window.screen.width < 600){ $.getScript(" 1.2.0.min.js"); }; }); Now load the page in your mobile device emulator. How it works... If the emulator successfully spoofs the device width in the request, you will see the jQuery Mobile version of the HTML page. In your desktop browser, no matter what size your browser window is, you will not be able to load the jQuery Mobile script. jQuery's $.getScript() is a function that loads an external script into the header. You can use it like we did in the recipe, to conditionally load an external JavaScript and additionally execute functions on its successful loading. 6 Optimizing Responsive Content In this chapter, you will learn about: ff Responsive testing using IE's Developer Tools ff Browser testing – using plugins ff Development environments – getting a free IDE ff Virtualization – downloading VirtualBox ff Getting a browser resizer for Chrome Introduction The recipes in this chapter cover a broad range of topics. There is no code covered in this chapter, but the recipes fall under a more functional umbrella. This chapter talks more about the tools you will use to develop and test code. Here we will make sure that our code works the way we want it to. While this topic may seem uninteresting, it is as important as honing your skills in design and development. No amount of confident boasting makes a frontend developer immune to errors, and there are simply too many things that can go wrong as a project grows. Please go through these recipes and try out the tools, they will make your work easier and less prone to errors down the line. Optimizing Responsive Content 140 Responsive testing using IE's Developer Tools Having a responsive design also includes having an optimized design for all of the prolific browsers, which is without equivocation, the least exciting aspect of Responsive Design. There is no way to sugarcoat this, many features of HTML5 and CSS3 are not supported even in the future versions of Internet Explorer, and those that are supported can sometimes be rendered incorrectly. To add more madness, Versions 7, 8, and 9 all behave differently, and there are countless users who just cannot or will not update their browsers. There's also the problem of a number of companies having invested in web software that only runs on older versions of Internet Explorer. This lack of updating has been solved by other browsers such as Chrome and Firefox; the Internet Explorer team really needs to catch up. However, because you want your work to always look good no matter what browser it's in, the responsibility is yours to make it work for every browser. Getting ready Talk to your clients and fellow designers on the project about what levels of support you want to provide for Internet Explorer users. There are a few strategies possible for supporting the older versions of Internet Explorer. Talk about how much additional work each will require to support older versions of Internet Explorer, how much it should cost, and who should pay for it. The last thing you want is to launch your clients' brand new web project and them starting to complain that it looks broken in their favorite, degraded old browser. The first question to ask is: what can you do with Internet Explorer F12 Developer Tools? The answer is, you can use it to debug the rather wonkish way in which Internet Explorer is displaying your code, and to toggle between the different versions of Internet Explorer to see how your site looks in each. How to do it... If you don't use a Windows computer, you won't be able to natively get a hold of Internet Explorer F12 Developer Tools. That doesn't mean that you simply forget about testing for IE and hope what you do works. There are legions of web pages and plugins that promise to accurately emulate the quirks of IE's multitude of versions. I have tried many and found that there was not one that actually stood up to testing against the original IE Developer Tools. So after much trial and failure, I found that the only dependable way to test for IE, without having to go and buy several computers just for testing, was to use virtualization. I have a few instances of Windows on virtual machines, with different versions of Internet Explorer installed. I have found that it's the only way to be sure. If you want to learn how to get started with virtualization, see the Virtualization – Downloading VirtualBox recipe in this chapter. Chapter 6 141 So once we have started up our Windows machine and updated to the latest version of Internet Explorer, let us see what the F12 Developer Tools can do for us. Either press F12 on your keyboard or click on the gear icon on the toolbar at the top-right corner of the screen to display the F12 Developer Tools. This is demonstrated in the following screenshot: The first useful thing you can do here is click on the pointer icon and move your mouse over the browser window to the element that is misbehaving. While the mouse is traveling, you will see that the element your mouse is moving over gets a white border around it. Once you see the white border around the element you want to inspect, click on it; the HTML pane will then bring that line of HTML code into focus in the left-hand side window, and its CSS on the right. In the CSS pane, you can edit the tree of CSS attributes for each element. If you want to add a CSS attribute, click on the Attributes button. By scrolling down to the bottom of the page, you can add a new name and value pair for the attributes. You can use these two tools to test out different CSS attribute variations or debug some strange IE behavior. Optimizing Responsive Content 142 The other useful tool is the Browser Mode select menu. You can use this tool to toggle between the different browser versions. This is a good tool to do on-the-fly checking of your work. Here, you can also test out your IE-specific stylesheets. You can see this in following screenshot: How it works... According to MSDN, the F12 Developer Tools represents the actual way in which the Document Object Model (DOM) interprets the page, and not the code you actually wrote. There's more... An additional pitfall you may fall into occurs when you are designing a site that may be accessed as internal software or on the same domain as the intranet. Internet Explorer will use Internet Explorer 7 Compatibility View as the default rendering view. Chapter 6 143 Compatibility mode was a feature added in IE 8 so that websites that were developed for the older standards could still work in the new browsers. Often, people's browsers are set to render intranet sites in compatibility mode. To make a site that is built for IE 7 work in the most recent Internet Explorer, you would have to set this tag to render it at the desired rendering version. To force the browser to always render this using the most recent rendering engine, you'll need to specify the following tag to prevent this. Browser testing – using plugins Testing is a big deal in any and all development processes. For some, the idea of testing is incorrectly perceived as a sign of poor workmanship or criticality of their work. This idea could not be more wrong. On the contrary, rigorous and thorough testing is the only way to ensure that your software approaches a state of perfection. I consider myself very fortunate to work with QA testers whose role is to test the work of the development team. Having had to do all of my own testing (in a previous life), I can say that this is a luxury. In this recipe, we will discuss a specific area of testing, cross-browser testing. Not too long ago, this was less complicated, and more challenging at the same time. The idea of testing a web project for mobile devices was not very common; it was simply not expected to look remotely similar, or even display the same content. Therefore the number of devices you needed to test for were usually limited to what you could spin up in a virtual environment, and they were all desktop devices. The tools were also limited, and were often only virtual desktops with older browser versions. Remember those stubborn people who refused to move beyond IE6? One approach to browser testing is to simply get your credit card out and buy every device you think it would be plausible for your software to be viewed on. I have never actually met anyone who has done this, but I think one or two of the fairy tales I read to my children spoke of this sort of phenomenon happening. This is not a practical solution for people who work for money. This has resulted in a market of paid and free cross-browser testing tools popping up on the Internet. Getting ready If you were starting to think that this is going to be an expensive recipe, calm down. There will be no need to go out and buy every new mobile device on the market. There are plenty of emulators that will cover most of your bases. Optimizing Responsive Content 144 How to do it... I have scoured the Internet and built a list of free tools for you to use for testing. Go through the list with me and check them out. Open one of your previous responsive web design (RWD) recipe project files in a browser tab to continue. For each of the simulators, you will have to open the file by entering it into the simulated browser's address bar. If you have not done any of these or simply do not have the files handy, go to the Packt website and download them. On to the simulators. First let's look at online browser simulators. Go to webapptester. Here you can test you RWD site on a web simulation of iOS devices. It can read your localhost files. You can toggle between the portrait and landscape modes and choose iPhone versus iPad. It's simple enough and you don't need to install any complicated applications or plugins. This is good if you need something in a pinch, want to test fast, and don't want to install anything. You can see the simulator in action in the following screenshot: Chapter 6 145 There is another handy web-based iOS simulator at You can get the portrait versus landscape and iPad versus iPhone (including iPhone 5) options here as well. This one too can view your localhost server. I keep mentioning this because there are too many web-based emulators that did not make it to this list for that reason, including some commercial emulators. The next screenshot displays this web-based emulator: Next let's look at some application-based browser testing tools. The Ripple browser plugin is an excellent testing tool. It can be downloaded at https:// This emulator blows the others out of the water. First, it does the same job as the others (that is, emulating the iOS devices), but it does it well. This one does so much more than what you need, but it will do everything you need for testing for the future mobile integration of your web apps. Let us get started by finding and installing the Ripple browser plugin. That's an easy task. Just go search for it. Remember when things used to be hard? Optimizing Responsive Content 146 Once you get to the Google Chrome Web Store, click on the big blue button and install the browser plugin. See the following screenshot: Chapter 6 147 Once it is installed, you will see a new browser button with blue ripples appearing next to the address bar of your Chrome browser. In your browser, go to your responsive web app. Next, click on the Ripple plugin button, and then click on Enable when a menu pops up asking whether you want to enable the Ripple plugin. The contents of the browser window transform to display an emulation of the device, which displays the mobile version of your page. In addition, you will notice a number of toolbars full of amazing settings and tools. Let's explore some of these. Most of them are beyond the scope of what we are doing, but you should still take note of these. These come in handy as you develop more advanced mobile web apps. You can see the numerous settings for Ripple in the next screenshot: Optimizing Responsive Content 148 First, click on the menu at the top-left corner of the screen to reveal a number of different mobile devices. Under that, you can select either the landscape or portrait orientation. As you go through the different simulated devices, you will see that there is an information panel that gets updated with the technical specs of the current simulated device. When you are done testing, simply click on the Ripple button again and select the Disable option. There are a number of other awesome tools in this simulator that are outside the scope of this book. Spend some more time on your own to discover useful tools to use for future mobile web app projects. Now let's move on to the next browser testing tool. The Opera Mobile Emulator is located at mobile. When I first saw this, I nearly skipped it, because it's Opera. Even though it's a serious browser project, I had gotten used to ignoring it for testing. It really is a respectable browser for mobile devices. I'm happy that I tried it out anyway. I was surprised to find that it has a number of options, and you really could use it to simulate a number of devices. It turns out to be a good mobile device browser testing tool to test a project on multiple Android devices. That's an important statement; note that I said Android devices, it means that it only tests those devices. It does, however, allow you to create and save custom screen sizes and settings. Let's jump straight to installing it and setting some custom screen sizes. To find it, use your favorite search engine and type in Opera Mobile Emulator. This should lead you to a page to download the Opera Mobile Emulator specific to your operating system ( Once you have downloaded and installed it, launch the application. When the application loads, you can see that there are a number of defined devices you can choose from on the left-hand side of the screen. Select any one of those devices and then click on the Launch button. See the following screenshot for demonstration: Chapter 6 149 We can also create custom device profiles and save them. Since there are no iPhone device settings, we will setup a custom screen for the iPhone. Select Custom from the Profile list. Next, in the Resolution drop-down menu, select a resolution of 320 x 480. Then under the Pixel Density drop-down menu, click on Add, and add 326. Now click on Launch. You can also click on the Save or Save As... buttons to save your profile. The dimensions for iPhone 4 are 640 x 960, and 640 x 1136 for iPhone 5. This is displayed in the following screenshot: One important feature of the Opera Mobile browser for your desktop is that you can use it to debug your code! To use this tool, download and install Opera for desktop devices; go to www. Next, open it and then under Menu, go to Tools | Advanced | Opera Dragonfly. In Opera Dragonfly, in the right-hand side window, find and click on the Remote debug configuration button, and then click on Apply. Then in your mobile browser emulator, in the address bar, enter opera:debug and click on Connect. Now you can debug your mobile code. Development environments – getting a free IDE Throughout this book, I've often referred to developing code in an IDE, or integrated development environment. The IDE is the toolset of the developer to create and manage code. There are many out there, free and paid, which you can use to help produce good code. Which IDE should you choose? That depends on a number of factors. Cost would be an important factor; Visual Studio can cost hundreds of dollars, and even more for additional auto-suggest plugins. The expensive IDEs are great as long as someone else is paying for them! Optimizing Responsive Content 150 Getting ready For this recipe, let us take the easier, cheaper route and install a good, free IDE. I spent some years working as a scientist, and because nine out of ten scientists prefer NetBeans, you might hypothesize that I use NetBeans. I can tell you that your hypothesis is empirically correct with a 90 percent probability. You might think that an enhanced notepad is a sufficient tool to build your applications. This may be the truth; your notepad is sufficient to write some code. But using a development environment brings much more than just a big program to write your code in. There are features such as enhanced project organization, autosuggest, and community-developed plugins for nearly every type of project or special function imaginable. How to do it… To get NetBeans, you can go straight to the NetBeans site at and click on the big orange Download button. The next page has a grid of options for the NetBeans download; you can either select the PHP option, or the "All" option to get the IDE package you need for frontend development. But before you download anything, there is another piece to the puzzle. NetBeans runs on Java, and both OSX and Windows do not come with Java preloaded. See the following screenshot: Chapter 6 151 If you already have Java Development Kit installed, continue with the download and install process. If not, go to the Java JDK site instead at java/javase/downloads/index.html (if that URL does not work, just search for Java JDK, and then click on the Downloads link). Here you can download a package of the latest stable NetBeans release with JDK. It's a large file, so start the download and go get some coffee. Expand the downloaded package; the install process will take care of the installation of the IDE and JDK. Next, open NetBeans. You should see the file and project browser on the left-hand side pane of the IDE. If not, and you are unable to open any of your projects, then it does not have the Web Development plugins activated. Open the Tools menu and select Plugins. In Available Plugins, find the PHP plugin and activate it. Your IDE will ask to restart. After restarting, you will see the Projects and File panes on the left-hand side in the IDE. This is displayed in the following screenshot: Optimizing Responsive Content 152 How it works... The NetBeans Integrated Development Environment is built in Java and therefore needs JDK to run. It comes as a base IDE; you download and install the plugins you need for your specific project. Additionally, because it is open source, people can develop more cool and useful plugins. There are testing, autosuggest, language, and other plugins continuously being developed. So try to be brave and experiment with some to see whether they enhance your development work. Virtualization – downloading VirtualBox Virtualization is one of the keystone tools in the developer's toolbox. It is used in a number of different phases of the development process. Our focus for this recipe will be on testing. But first, I want to mention how it can be used further upstream in the process. Setting up virtual machines allows you to use your preferred operating system and toolset in a shop that only provides and supports different ones. For example, if you need to be able to use Visual Studio but don't want to use Windows, you can spin up a virtual machine and develop applications on it. You can also use a LAMP stack on a virtual machine and spin it up. Virtualization is a resource-intensive computing task. It won't take much to bog down your system when you are running a virtual machine with an IDE, a web server, and a remote desktop viewer, and it might just drag your system down to a screeching halt. So my advice is to load up on memory before you try to load up multiple VMs. Getting ready Before we go on to the simple task of spinning up a new VM, let us explore some of the rationale behind what we are about to embark on. The first reason is, Internet Explorer. Do I need to say anything else? I will anyway, for the uninitiated. There is an earth-shattering collective groan whenever a designer has to make his beautiful modern website terrible for it to work in any version of Internet Explorer. It isn't enough that it looks good in IE9; we will also be required to make it look presentable in IE8. Why is this the reality of web development? Because people are slow when it comes to upgrading; businesses are even worse in this matter. To get a picture of the ratio of your site's visitors that are using deprecated browsers, install Google Analytics and monitor the types of browsers used to visit your page. You might be horrified to find that 20 percent of your traffic is using Internet Explorer 7, and you need to market to them. You cannot run IE7 along with IE9 on the same computer. So the solution is starting to visualize its problem. To be able to test your site to make sure it's optimized, or at least, degrades well for every old version of Internet Explorer, or is responsive for mobile devices, you can employ virtualization. Spin up a new virtual machine for each different browser version that you need to test for. For the rest of this recipe, we will go through the process of creating new virtual machines. Chapter 6 153 How to do it... VirtualBox is a free software made available by Oracle. There are other virtualization software out there, such as VMware, which are not free. To download VirtualBox, go to and download it from the Downloads page. Once downloaded, the install process is as straightforward as anything else. In OS X, unpack it and drag it into the Applications folder. In Windows, it gives different options. I would not try anything tricky at this point; it will work great with the default options. Both versions will set up directories for the virtual machines in your profile's home directory. Next, you will need the operating system install disk or disk image (ISO) for the guest operating system you want installed on the virtual machine. When you are ready and have your OS installation software ready at hand, click on the New button at the top-left corner of Oracle VM VirtualBox Manager. This will start up a wizard called New Virtual Machine Wizard. See the following screenshot: You will be asked to enter a name and OS type on the next screen. Next, select the memory to allocate for the VM. The recommended base memory size is 192 MB. The next screen asks you to either create a new disk or use an existing disk. When installing a new OS from a disk or image, you will want to select Create new hard disk. On the next screen, use the already selected default, VDI (VirtualBox Disk Image), and then select Dynamically Allocated. You will then be asked to name the folder that holds the virtual image, and also the size of the virtual disk; the default is 10 GB. The summary pages follow, where you can review your choices before you proceed. Thus far, we have only created the virtual machine, the equivalent of turning on a new computer with no operating system. Optimizing Responsive Content 154 To finish what we have started, we need to start up your new virtual machine and install Windows on it. Select your new virtual machine and start it to initiate the First Run Wizard. It will prompt you for the installation media; here you select your disk or image ISO. Select your installation media, continue to the Summary page, and then on to the OS installation process. This goes pretty fast since it is a virtual drive. I'll skip the ins and outs of installing your Windows Desktop Operating System software; there are no secret best practices here, just click through the defaults and keep going. While I was writing that paragraph, my VM finished installing the OS. I told you it was fast. Once it starts up, you can use the default browser version or get an updated version. This depends on the needs of your project. I recommend having a separate VM for IE9, IE8, and even IE7. Once you get it running, you should have a good, clean, working version of Windows XP. See the following screenshot: Now that the virtual machine has its OS installed, fire up the browser and point it to the IP address of your host computer. If you have your local web server running, and have not monkeyed around with your VirtualBox network settings, you should see the files on your local web server. You can use this to test your web design to make sure the desktop version works well for all of your desktop audience, even those using IE7. Chapter 6 155 You don't need to host multiple versions of Chrome or Firefox anymore, they have all started auto-updating. The old Firefox version is a thing of the past. That covers testing for desktop. Before we move on to the next chapter, let us take a look at how we can use VirtualBox to test for mobile devices as well. There exist out there on the Internet, downloadable virtual machines that already have Android installed. I found a few downloadable resources at org/download. By doing a search for Android-v4.7z, I found a good download link here: &id=8838. It offers you a link to download it from VMLite-Android-v4.0.4.7z. Download and extract the virtual image to your hard drive. Let us see what happens when we open up one of these Android images with VirtualBox. After you have downloaded an Android image, spin up a new virtual image. When asked to select the OS type, choose Linux from the list of operating systems in the drop-down list and choose Other Linux for Version. See the following screenshot for demonstration: On the Virtual Hard Disk screen, select Use existing hard disk, and then in the select dialog box, browse to the folder you extracted to your drive. Inside it is a *.vmdk file. Select it to load it into your new virtual machine, and click on Continue. Optimizing Responsive Content 156 Continue beyond the Summary page, and your Android emulator will spin up and be fully operational. Now you can test your apps on a true Android emulation as shown in the next screenshot: How it works… Virtual machines allow you to install an operating system on a generic type of emulated computer. You can copy, edit, and delete the virtual machine on the fly, and it allows you to jump between VMs easily. In these, you can do a number of things; take a snapshot, and if something goes wrong, just start over completely. It is a good practice to use VMs and not need to worry too much about getting your OS to run Apache. Getting a browser resizer for Chrome Imagine yourself dragging your browser window's bottom corner left and right to resize it over and over again, watching for the points where your best visual estimation tells you it should be hitting the breakpoint of your media query and eloquently respond by showing a new optimized display of your website. The far from small problem that you have is you have no idea where your breakpoints will hit because you have no real clue of your current browser size, and no reliable way to set it to its desired size. Looks silly doesn't it? The co-worker sitting behind you thinks so too. There has to be a better way. There is! Now you can stop your co-worker from laughing at your browser window antics. Chapter 6 157 Getting ready There are some websites out there in Internet-land that can resize your browsers to the most popular breakpoints. However, these are difficult to find and are not reliable. I have found that the best option is to install a good browser resizer plugin. How to do it... The best solution I have found is the Chrome Window Resizer plugin. To get it for Chrome, search for Window Resizer in your favorite search engine and click on the link to go to the plugin's page at the Chrome Web Store. Click on the big blue button that says Add to Chrome. It's a fairly brief and easy installation. Go through the process and say yes every time you are prompted. See the resizer in action in the following screenshot: Once you are done, you will see the world's tiniest browser perched next to the address bar of the Chrome browser; no, just kidding, it's an icon. When you click on it, you will see a drop-down menu of different window sizes. These sizes were chosen as they are the most common size screens found in the wild of Internet-land. Optimizing Responsive Content 158 If you have an analytics tool such as Google Analytics installed in your web project, you can get a good picture of what your viewers are like. With respect to this recipe, you would want to look at the browser screen sizes. Navigate to the Audience tab and expand the Technology toggle element to expose the Browser & OS link. You will see the breakdown of your audience's browsers. On that page, change the Primary Dimension: to Screen Resolution. Now you will be able to see the most common screen sizes of your site's visitors. This tool should give you an insight into areas to concentrate on in your design. See the following screenshot: Analytics will provide some good intelligence about your user's screens, but remember that people often use only part of their screen for the browser window. Back to the browser resizer plugin; try out some of the built-in sizes on your project and see how it responds. This tool will be a great testing tool in your Responsive Design toolbox. Chapter 6 159 In addition to the set sizes, you will see that the drop-down menu also has an Edit resolutions menu item. Here you can add any screen sizes that you discover on your analytics screen. Based on my analytics report, I might want to start by adding 1920 x 1080, 960 x 1080, 1772 x 1038, and 886 x 1038. I have demonstrated this option in the next screenshot: How it works... This highly useful tool plugs right into your browser to work its magic by emulating different screen resolutions. It's not really magic, even though good software can appear to be magical sometimes. With Analytics tools, you can design specific optimizations for your website viewer's screens. 7 Unobtrusive JavaScript In this chapter you will learn: ff Writing "Hello World" unobtrusively ff Creating a glowing "submit" button with the event listener ff Making a button stand out when you hover over it ff Resizing an element with unobtrusive jQuery ff Masking a password with unobtrusive JavaScript ff Using an event listener to animate an image shadow Introduction The concept of unobtrusive JavaScript fits right into responsive design. By keeping your interaction layer at an arm's length from your presentation layer, you can build a great degree of flexibility into your web app. Because mobile devices have very different input methods, you may need to call a function through a different event. You may want to create a desktop version of a page with JavaScript and use jQuery Mobile instead for your mobile version; with the same template files, by using unobtrusive JavaScript, this is not a difficult task. Writing "Hello World" unobtrusively An important facet of responsive design is interaction. As we know that mobile devices and desktops have very different user interfaces, we cannot expect that our JavaScript interaction scripts will work across all devices. An illustrative example is the .mouseover() or mouse hover event listener. The mouse is not attached to a touch screen device, so any misdirected attempt at the .mouseover() event would likely function as a .click() event. The solution to this is to fully remove your interaction script from your templates. Unobtrusive JavaScript 162 Getting ready This method is referred to as "Unobtrusive JavaScript". Here, instead of embedding scriptlets like onclick() in your HTML template, you can create an external JavaScript that runs through a series of event listeners to set up your interaction. How to do it... Let's start with a simple example; we will create only a button and an alert. Many JavaScripts start as a test; in essence, I will create an event listener and then debug it with an alert. We start by creating an HTML page with a simple submit button. There you go, that was a simple task, but not very exciting. That's just a basic submit button, even though it did not submit anything. So let's make this more interesting, one step at a time. Start by adding some custom text to the button, so that we at least have some expectation of what might happen when this page is ready. We add value="Say Hello". That's enough for the body tags, next we add a script tag to the header: Inside the script tags, you will need to add an event to start the JavaScript. The script would otherwise not run without the $(document).ready(function(){...}); function: $(document).ready(function(){ //do something here }; Inside this function, replace //do something with a listener for the :submit button click event that fires a function to somehow put Hello World on the screen: $(":submit").click(function() { //write "Hello World" }); So far, we have created a JavaScript that loads as the page loads and listens for when the user clicks on the button. When the click event occurs, a function executes, but right now that function is empty. Our next task is to create the method of adding the "Hello World" text to the page. Chapter 7 163 Inside the function, we want to append the "Hello World" text to the parent element of the :submit button. Since the :submit button is the object from which the method is firing, we can reference it by using $(this) in jQuery. To attach the "Hello World" text, use the jQuery .append() method: $(this).parent().append("Hello World"); The jQuery will append the "Hello World" text to the end of HTML's body tag. To have more control over where the text is appended, wrap the button in a parent div element. Open the HTML file in the browser and test the button's functions. If pressing the button does not make the text Hello World appear under the button, then something has gone wrong. Go back through the tutorial and see where you went astray. Before continuing, we can't just let the text be plain text. We want to be able to do more with this later. Mark it up with a paragraph tag that includes an ID attribute, helloWorld. At this point, we have accomplished our basic intention, to clicks a button, and write Hello World. That is good, but not good enough; because we always over-deliver, don't we? Outside the .click() event function, add a variable foo for the string Hello World. Next, replace the .append(...) function's internal Hello World text with the foo variable. Removing the text from the method and replacing it with a variable makes things easier to work with, and is only a small step towards improving this function. Refresh and test your page to make sure everything still works. Inside the body tags, we are now going to personalize this page by sending the text to the script through a form input element. Inside your HTML body tags, enter a text input element with id="bar" and placeholder="Enter your name". To receive the text from our input box, we need to add a new variable bar inside your function. Set it equal to the value of the input: var bar = $('input').val(); Next, update your .append() method by changing it to include foo, bar, and some new text, all wrapped in a styleable element: $(this).parent().append("
    " + bar + " says " + foo + "!
    "); Now, when you refresh this page, you see that the text box has been added. Try it out by entering your name in the input box and watch the results. Unobtrusive JavaScript 164 This is great, but not complete. Now it's time for some cleanup. Let's go through some scenarios that we want to avoid. We do not want to be able to submit an empty input or keep adding more lines of Hello World. First, take care of the blank input box. Let us add an if condition to check that the input text is not blank before we append it to the HTML. After the line that gets the input value, add a new line with the conditional statement checking that the variable is not a blank string. This condition wraps the append statement. Also add an else statement for when the input is a blank string. Inside it, copy the .append() method with text reminding the user to enter a value in the text input. var bar = $('input').val(); if (bar != ""){ $(this).parent().append("
    " + bar + " says " + foo + "!
    "); } else { $(this).parent().append("Please enter a your name!") }; This adds some validation to your form that will nag your user to enter your name if the submit button is clicked with a blank text box. There are two more clean-up items left, so hang on for a few more minutes. First, we want the appended HTML to reset each time. So add a line right after your if conditional statement and before the else statement, removing the .newText element added earlier. $(".newText").remove(); Finally, right before the end of the if conditional, reset the input form to have a blank value by using the .val() method. Also add an ID attribute to the text input to connect the value to the input. $('input#fooBar').val(""); That's it! We have kind of over killed it, but we have a pretty good Hello World web app. How it works... Unobtrusive JavaScript works by loading up the script on page load and operates by using listeners to wait for specific events to occur on the page. This may be an adjustment in how you write, but then there is an advantage in being able to separate the interaction from the presentation. Chapter 7 165 Creating a glowing "submit" button with the event listener Working with forms is often an overlooked aspect of most web design topics, even more so, responsive web design. Often non-transactional pages do not use forms beyond the simple Contact Us page, therefore the form design is often an afterthought. However, in the realm of transactional e-commerce and Software as a Service industries, forms are the most important elements the user interacts with. In this world, responsive design is more than just responsive layouts and images, it includes thoughtful interaction. In this recipe we can imagine a scenario where a user is at the end of a form process and is ready to submit the form. It's not an uncommon occurrence to see a person rather comically click the submit button and watch the page just sit there, seemingly doing nothing (but it is actually performing the post action of the form) and react by clicking the same button again and again and again. In the simple Contact Us scenario, this could generate some additional form submission e-mails, but in the transactional situation, this could activate a long string of business logic and become disruptive to other processes. On the user side, there can be the idea that if nothing happens immediately after clicking the submit button, something has gone wrong and the site has failed; and the end result is the abandoned transaction and the damaged trust of your site. There are a number of things you can and should do about this. One of them is adding visual cues to let the user know that they have successfully clicked the button, and something is going to happen. Consider the transaction being performed behind the scenes and the time it will take. If you anticipate a long wait, be aware that your user might not know this. People usually expect that in the Internet world of instant gratification everything is instant, and anything that isn't instant is broken. Getting ready In the Writing "Hello World" unobtrusively recipe, we wrote a simple submit button function. We can use this as the basic building block for this recipe. If you do not have that code handy, you can get the finished version of it online at Packt Publishing's website ( How to do it... First we need to break out the meat of the submit function into a separate function that is called by the .click() event function. Cut out everything from inside the function and paste it outside the $(document).ready(function() {...}); function. Replace everything that you have cut out with a function call to the new function. In the function call, include the declared variable foo with the ID value of $(this) by the .attr() method. Then, wrap the code you pasted in a new function of the same name, and assign it to receive the two variables. Finally add an ID attribute to your submit input. Your code should look similar to the following: $(document).ready(function(){ Unobtrusive JavaScript 166 var foo = "hello world "; $(":submit").click(function(){ formAction(foo,$(this).attr("id")); }); }); function formAction(foo,id){ var bar = $('input').val(); if (bar != ""){ $(".newText").remove(); $("#" + id).parent().append("
    " + bar + " says " + foo + "!
    "); $('input#fooBar').val(""); } else { $(".newText").remove(); $("#" + id).parent().append("
    Please enter a your name!
    "); }; }; First things first, remove the bar variable from the formAction() function and paste it inside the .click() event listener function. This builds the variable on every click event. Now onto building new functions; add a new function to the JavaScript called buttonAnimate() and call it after the formAction() call in the .click() event listener. In the buttonAnimate() function call, send the bar variable. Finally, add the bar variable to the formAction() function call and the function declaration variables. The key development is that we have added the input value as a variable in the .click() event listener function and sent it to the two function calls. With that out of the way, we can now start writing in our new function of animating effects on the button. Take a small break and get some coffee. We are going to temporarily shift gears and write some CSS. Add a stylesheet to your project; inside the stylesheet, add two classes, .valid and .invalid, which will act on the button for its two different response states, valid and invalid. The pass scenario occurs when the text is entered into the form when submitted and the fail scenario occurs when the submit button is pressed without the text being entered in the form element. .valid{...} .invalid{...} Chapter 7 167 In the valid state, we have submitted the form with text in the input box. We want to add CSS to the button that represents a positive state; the button has been activated, indicating that something correct has happened. I have added a border, shadow, text-shadow, background color, text color, and border-radius. This will be a sufficient indicator that something expected has happened. .valid{ border:2px solid #000; -webkit-box-shadow: 1px 1px 5px 3px #0000ff; box-shadow: 1px 1px 5px 3px #0000ff; text-shadow: 1px 1px 1px #666666; filter: dropshadow(color=#666666, offx=1, offy=1); background-color:rgb(150, 150, 255); color:#ffffff; -webkit-border-radius: 5px; border-radius: 5px; } We add the same CSS style types to the invalid state, where the user has submitted the form with no text in the input box. In this instance, we want to give visual clues that something has gone wrong, and prompt the user for their attention to try again. In this scenario, orange and red are good colors to signal that an error has been made. In addition, we also add a CSS blur effect with a transition. .invalid{ border:2px solid #ffff00; -webkit-box-shadow: 1px 1px 5px 3px rgb(255, 0, 0); box-shadow: 1px 1px 5px 3px rgb(255, 0, 0); background-color:rgb(255, 133, 0); color:#ffffff; -webkit-border-radius: 5px; border-radius: 5px; -webkit-filter: grayscale(0.1) blur(1px); -webkit-transition: border 0.2s ease; -moz-transition: border 0.2s ease; -ms-transition: border 0.2s ease; -o-transition: border 0.2s ease; transition: border 0.2s ease; text-shadow: 1px 1px 1px #666666; filter: dropshadow(color=#666666, offx=1, offy=1); } Unobtrusive JavaScript 168 That is all the CSS we are going to write for this recipe. Next, we are going to write the JavaScript to connect the two different styles to the actual states. Way back earlier in this recipe, we created an empty function called buttonAnimate() that received the variable bar, now it's time to build that out. Inside it, add the same if conditional statement to check if bar is an empty string. If it is, add the valid class to the submit button, and if it is not, add the class invalid. This added invalid class alerts the user that something has gone awry, and an action needs to be taken. if(bar!= ""){ $(":submit").addClass("valid"); } else { $(":submit").addClass("invalid"); }; When the appropriate action is taken, that is, when the user clicks on the form element to enter text, the button should be reset to its original state; technically, the new added class should be removed. That code is as follows: $('input#fooBar').focus(function(){ $(":submit").removeClass('invalid') }); The final bit of cleanup left is to remove either or both classes from the beginning of the if and else conditions. Use the .removeClass() method on the submit element twice to remove the class opposite to the class to be added. function buttonAnimate(bar){ if(bar!= ""){ $(":submit").removeClass("invalid"); $(":submit").addClass("valid"); } else { $(":submit").removeClass("valid"); $(":submit").addClass("invalid"); $('input#fooBar').focus(function(){ $(":submit").removeClass('invalid') }); }; }; Chapter 7 169 Now reload and test out the page and see the magic you created. It will look like the following screenshot: How it works... jQuery is a great library that does the heavy lifting for you to create great web apps quickly and with very little code. In the old world of plain old JavaScript, this functionality would have cost you much more code and time. It has the library functions to read the form's values, append HTML easily, and toggle the CSS classes on and off. All you need is to implement some jQuery methods and CSS, and the rest is done for you. Making a button stand out when you hover over it Sometimes the big challenge in responsive design is being able to really over deliver a project when the requirements are only to build something that is just good enough. A button is an opportunity where you can deliver that extra level of polish for a product that astonishes the users. If we were not over delivering, we could just throw a :hover selector at this and be done. However, in this recipe, we're going to make a button that shines like a boss when you hover over it. Unobtrusive JavaScript 170 Getting ready Know the pitfalls of over delivering. Giving more than asked is something we should all strive for, but beware of setting unreasonable expectations that you cannot meet, and drive an otherwise successful project into failure. In a previous recipe, we created a form with a button that animated when you clicked on it. For this recipe, you can continue working with that code. You can also go and download the code for that recipe, or this recipe for that matter. Or you could just make a form and button element. It's not that hard. How to do it... We are essentially starting with a page with two form elements; an input box and a submit button. As I mentioned earlier, these were built in a previous recipe; you could also just build them here. The JavaScript we built in the recipe will work with the new interaction, but is not required. The input element has the id attribute fooBar, and the button has the id attribute submit. Let's start by making the default look of the button more interesting. Add to your CSS a style for the input#submit element. Inside the style, add a blue background color, a white font color, an 8-point border radius, a 14-pixel font size, and padding of 5 pixels and 8 pixels. This can be done using the following code: input#submit{ background-color:blue; color:white; border-radius:8px; font-size:14px; padding:5px 8px; } Now that the button's default look is defined, let's talk about the interactive design. Here, we get into the actual advantage of using JavaScript for a .mouseover() event instead of a CSS :hover selector. I would like to interact with the form element and query if text has been entered in it or not. If text is entered, we want a special visual cue indicating that the form is ready to be submitted; if no text is submitted, a strong visual cue should tell the user to stop and go back to check their form again. Chapter 7 171 First, if the form is ready to be submitted, the button will appear to extend out towards the mouse pointer and turn green. The CSS will include a green background color with the !important override, a box shadow, and a text-shadow. See the following code snippet for the exact CSS syntax: .buttonLight{ background-color:green !important; -webkit-box-shadow: 1px 1px 2px 1px green; box-shadow: 1px 1px 2px 1px green; text-shadow: 1px 1px 2px #666666; filter: dropshadow(color=#666666, offx=1, offy=1); } Alternately, if the form input is empty, the button will turn red and retract away from the mouse pointer. This CSS will have a red background color with the !important override, and inset shadow, and a text shadow that makes the text blurred. .redButtonLight{ background-color:red !important; -webkit-box-shadow:inset 1px 1px 3px 2px #663535; box-shadow:inset 1px 1px 3px 2px #663535; text-shadow: 0px 0px 2px #fff; filter: dropshadow(color=#fff, offx=0, offy=0); } That's the extent of the CSS we are creating. It's time to build the interactivity. In your header, if you have not already done so, create the opening and closing How to do it... The first task is to create in your HTML body, two input elements. The first has the attributes of type and ID of the password. This will be the encrypted version submitted in the form, but will ultimately be hidden from view. The second will have the ID altDisplay and be disabled, so the user cannot click inside it. This one will be displayed on top of the other one and it will appear to be the one the user is typing into. At the end, we will add a style to hide the password field. That is all that is needed for the HTML body of the recipe, of course you can add other form elements as needed. In the header, add a JavaScript How to do it... First, create the body of your HTML file using a div element with the class wrap. Inside it, add an image with the class topRight. Next up; the CSS.
    Add a section for the CSS. First, add a text-align: center style to the body. Next, give the .wrap div element a width of 30%, and an automatic horizontal width. This is shown in the following code snippet: body{text-align:center;} .wrap{ width:30%; margin:0 auto; } .wrap img{ width:100%; height:auto; margin:80px 1%; border-radius:50%; -webkit-border-radius:50%; border:1px dotted #666; } The next set of CSS is varying the image class variations that will be assigned by the jQuery script depending on the mouse position. Each contains a differently angled box-shadow. Name the different classes topLeft, topRight, bottomLeft, and bottomRight. Each will have a shadow offset of 5 pixels, a spread of 2 pixels, and blur radius of 2 pixels. img.topLeft{ border-top: 5px solid #666; border-right:5px solid #999; border-bottom: 5px solid #999; border-left:5px solid #666; -webkit-box-shadow: -5px -5px 2px 2px #666; Chapter 7 181 box-shadow: -5px -5px 2px 2px #666; } img.topRight{ border-top: 5px solid #666; border-right:5px solid #666; border-bottom: 5px solid #999; border-left:5px solid #999; -webkit-box-shadow: 5px -5px 2px 2px #666; box-shadow: 5px -5px 2px 2px #666; } img.bottomLeft{ border-top: 5px solid #999; border-right:5px solid #999; border-bottom: 5px solid #666; border-left:5px solid #666; -webkit-box-shadow: -5px 5px 2px 2px #666; box-shadow: -5px 5px 2px 2px #666; } img.bottomRight{ border-top: 5px solid #999; border-right:5px solid #666; border-bottom: 5px solid #666; border-left:5px solid #999;| -webkit-box-shadow: 5px 5px 2px 2px #666; box-shadow: 5px 5px 2px 2px #666; } Excellent work so far. Now it is time to build the JavaScript. Inside your script tag, create the standard $(document).ready event function. Then, to start add a .mousemove() event listener function to the body. Inside it, create two new variables imgHorz and imgVert for the horizontal and vertical positions of the .wrap img div element. $("body").mousemove(function(e){ var imgHorz = ($(".wrap img").offset().left); var imgVert = ($(".wrap img").offset().top); }); Next, after the variables have been created, we create some conditions based on the variable values compared to the position of the mouse at the time of the event. If the results are true, then remove all CSS classes before adding one of the image classes. if(e.pageX < imgHorz && e.pageY < imgVert){ $(".wrap img").removeClass(); $(".wrap img").addClass("bottomRight"); }; Unobtrusive JavaScript 182 Then you will want to add three additional else/if conditions to add the other classes. The following code snippet shows the four conditions displayed: if(e.pageX < imgHorz && e.pageY < imgVert){ $(".wrap img").removeClass(); $(".wrap img").addClass("bottomRight"); } else if (e.pageX > imgHorz && e.pageY < imgVert) { $(".wrap img").removeClass(); $(".wrap img").addClass("bottomLeft"); } else if(e.pageX > imgHorz && e.pageY > imgVert) { $(".wrap img").removeClass(); $(".wrap img").addClass("topLeft"); } else if(e.pageX < imgHorz && e.pageY > imgVert) { $(".wrap img").removeClass(); $(".wrap img").addClass("topRight"); }; And that wraps up the JavaScript. One last thing, we also need to animate the transition between CSS styles. So, instead of adding more JavaScript, add a CSS transition to the .wrap img element (each browser needs its own transition command). -webkit-transition: all .5s linear; -o-transition: all .5s linear; -moz-transition: all .5s linear; -ms-transition: all .5s linear; -kthtml-transition: all .5s linear; transition: all .5s linear; Chapter 7 183 That was a fairly simple recipe, and the end result is a fun image element where the shadow follows the mouse around. The following screenshot is an illustration of this recipe: Unobtrusive JavaScript 184 How it works... This recipe measures the location of the image and the mouse on every .mousemove() event. The result of each is that a new shadow is applied to the object. Now it is important to think about what events are appropriate for mobile devices versus desktops. A .mousemove() event won't work as there is no mouse attached to a mobile device. From here, I would refer to Chapter 5, Making Mobile-first Web Applications, for a refresher on how to load JavaScripts such as jQuery Mobile for mobile devices. We built simple UI interactions using unobtrusive JavaScript. I hope that these simple scripts are not only useful examples that you could actually use in a project, but they also demonstrate effectively how to write JavaScript that could live outside of your template files. This fits into your responsive design when you pair it with mobile versions of the script that can be called to the mobile devices. Going forward, this will help you create more responsive and fluidly transitioning web projects. Live long and prosper, my friends. Index Symbols $.getScript() function 138 3D text creating, with CSS3 36, 37 :hover selector 169 tag 116 :submit button 163 A alternating rows styling, with nth positional pseudo class 39- 41 animate() method 172 append() method 163 ASCII 5 attribute selector 86 attr() method 165 B Blueprint grid layout about 84 using 85-87 working 88 Bootstrap framework about 99 using 99-103 working 104 border radius corner, curving with 46-48 border-radius property 48 browser resizer obtaining, for Chrome 156-159 browser resizing plugins using 112, 113 browser testing plugins used 143-149 button about 169 creating 170-173 creating, with relative font size 42-44 buttonAnimate() function 166, 168 C canvas used, for creating inner shadow 31-33 used, for creating outer shadow 31-33 used, for creating text shadow 29-31 used, for rotating text 33, 34 canvas element 29 Chrome browser resizer, obtaining for 156-159 user agent, masking in 109-111 click event 24, 161 content pseudo markup, adding to 41, 42 context.fillText method 33 context.strokeStyle method 33 cookie used, for delivering responsive image 8-10 corner curving, with border radius 46-48 CSS media query, adding to 55-59 CSS3 about 5 used, creating 3D text 36, 37 used, for rotating text 34, 35 CSS3 Box Shadows 24 CSS3 button glowing, for element load 21-25 186 D demo.html file 93 development environments 150 display property 70 div element 12 Document Object Model (DOM) 142 E element hiding, with media query 66-68 resizing, with unobtrusive jQuery 173-176 event listener used, for animating image shadow 179-184 used, for creating glowing submit button 165-169 F Fluid 960 grid layout about 80 URL 80 using 81-84 fluid grid 80 fluid layout based on rule of thirds 88-91 font shadow, adding to 44-46 formAction() function 166 G getContext() method 30, 32 GIMP about 6, 38 URL 38 glowing submit button creating, with event listener 165-169 Golden Grid about 88 URL 88 Google 112 Google Image Search 6 Gumby 960 Grid framework about 93 URL 93 using 94-97 working 98 H Hello World writing, unobtrusively 161-164 HTML5 5 I IDE about 149 obtaining 150-152 IE’s Developer Tools used, for responsive testing 140-142 image resizing, media queries used 13, 14 resizing, percent width used 6, 7 image shadow animating, event listener used 179-184 image sizes modifying, with media query 64-66 indexOf() method 175 inner shadow creating, canvas used 31-33 integrated development environment. See  IDE Intrinsic Ratios for Videos 13 Ipsum about 6 URL 6, 28 J Java JDK 151 JavaScript adding, for mobile browsers 137, 138 used, for delivering responsive image 8-10 jQuery 5, 24, 169 jQuery Mobile about 105, 161 list element, creating in 122-129 mobile native-looking button, adding with 129-134 second page, creating in 119-122 tags, adding for 116-119 K K.I.S.S. approach 135 187 L layout controlling, with relative padding 52-55 layout frameworks 79 list element creating, in jQuery Mobile 122-129 M max-width property, responsive layout 49-52 media queries used, for resizing image 13, 14 media query adding, to CSS 55-59 element, hiding with 66-68 mobile stylesheet, adding for mobile browsers 135, 136 used, for creating responsive width layout 59-63 used, for modifying image sizes 64-66 used, for modifying navigation 14-19 min-width property, responsive layout 49-52 mobile browsers JavaScript, adding for 137, 138 mobile stylesheet, adding for 135, 136 mobile native-looking button adding, with jQuery Mobile 129-134 mobile stylesheet adding, for mobile browsers 135, 136 mousemove() event 184 mouseout() listener 171 mouseover() event 161, 171, N navigation modifying, with media query 14-19 NetBeans about 150 URL 150 nth positional pseudo class used, for styling alternating rows 39-41 O onclick() method 162 online browser simulators 144 Opera Mobile Emulator 148 outer shadow creating, canvas used 31-33 P partial-fade class 24 password creating, with unobtrusive JavaScript 177-179 percent width used, for resizing image 6, 7 plugins used, for browser testing 143-149 pseudo markup adding, to content 41, 42 R relative font size button, creating with 42-44 relative padding layout, controlling with 52-55 REM 28 removeClass() method 168 responsive image about 8 delivering, cookie used 8-10 delivering, JavaScript used 8-10 responsive layout with max-width property 49-52 with min-width property 49-52 responsive padding creating, based on size 19-21 responsive testing performing, IE’s Developer Tools used 140- 142 responsive typography about 28 creating 28, 29 responsive web design (RWD) 5, 144 responsive width layout creating, with media query 59-63 Ripple browser plugin 145 Root EM. See  REM rotate method 34 rule of thirds 88 188 S Safari Developer Tools User Agent switcher, using 106-109 screen width video, responding to 10-12 second page creating, in jQuery Mobile 119-122 shadow adding, to font 44-46 smoothly transitioning responsive layout creating 68-78 T tags adding, for jQuery Mobile 116-119 text rotating, with canvas 33, 34 rotating, with CSS3 34, 35 text-masking used, for adding texture to text 38, 39 text shadow creating, with canvas 29-31 text-shadow property 37 texture adding, to text with text-masking 38, 39 transform:rotate property 34 Twitter Bootstrap framework. See  Bootstrap framework U unobtrusive JavaScript about 161, 162 used, for creating password 177-179 unobtrusive jQuery element, resizing with 173-176 user agent about 106 masking, in Chrome 109-111 User Agent switcher using 106-109 V video responding, to screen width 10-12 video-hosting sites 11 video tag 10 video-wrap element 12 viewport about 113 options 114-116 VirtualBox about 153 downloading 153-156 URL, for downloading 153 virtualization 152 Visual Studio 149 VMware 153 Thank you for buying HTML5 and CSS3 Responsive Web Design Cookbook About Packt Publishing Packt, pronounced 'packed', published its first book "Mastering phpMyAdmin for Effective MySQL Management" in April 2004 and subsequently continued to specialize in publishing highly focused books on specific technologies and solutions. Our books and publications share the experiences of your fellow IT professionals in adapting and customizing today's systems, applications, and frameworks. Our solution based books give you the knowledge and power to customize the software and technologies you're using to get the job done. Packt books are more specific and less general than the IT books you have seen in the past. Our unique business model allows us to bring you more focused information, giving you more of what you need to know, and less of what you don't. Packt is a modern, yet unique publishing company, which focuses on producing quality, cutting-edge books for communities of developers, administrators, and newbies alike. For more information, please visit our website: Writing for Packt We welcome all inquiries from people who are interested in authoring. Book proposals should be sent to If your book idea is still at an early stage and you would like to discuss it first before writing a formal book proposal, contact us; one of our commissioning editors will get in touch with you. We're not just looking for published authors; if you have strong technical skills but no writing experience, our experienced editors can help you develop a writing career, or simply get some additional reward for your expertise. HTML5 Mobile Development Cookbook ISBN: 978-1-84969-196-3 Paperback: 254 pages Over 60 recipes for building fast, responsive HTML5 mobile websites for iPhone 5, Android, Windows Phone, and Blackberry 1. Solve your cross platform development issues by implementing device and content adaptation recipes 2. Maximum action, minimum theory allowing you to dive straight into HTML5 mobile web development 3. Incorporate HTML5-rich media and geo-location into your mobile websites HTML5 Multimedia Development Cookbook ISBN: 978-1-84969-104-8 Paperback: 288 pages Recipes for practical, real-world HTML5 multimedia- driven development 1. Use HTML5 to enhance JavaScript functionality. Display videos dynamically and create movable ads using JQuery 2. Set up the canvas environment, process shapes dynamically and create interactive visualizations 3. Enhance accessibility by testing browser support, providing alternative site views and displaying alternate content for non supported browsers Please check for information on our titles Responsive Web Design with HTML5 and CSS3 ISBN: 978-1-84969-318-9 Paperback: 324 pages Learn responsive design using HTML5 and CSS3 to adapt websites to any browser or screen size 1. Everything needed to code websites in HTML5 and CSS3 that are responsive to every device or screen size 2. Learn the main new features of HTML5 and use CSS3’s stunning new capabilities including animations, transitions and transformations 3. Real world examples show how to progressively enhance a responsive design while providing fall backs for older browsers Responsive Web Design by Example ISBN: 978-1-84969-542-8 Paperback: 338 pages Discover how you can easily create engaging, responsive websites with minimum hassle! 1. Rapidly develop and prototype responsive websites by utilizing powerful open source frameworks 2. Focus less on the theory and more on results, with clear step-by-step instructions, previews, and examples to help you along the way 3. Learn how you can utilize three of the most powerful responsive frameworks available today: Bootstrap, Skeleton, and Zurb Foundation Please check for information on our titles




    需要 8 金币 [ 分享pdf获得金币 ] 3 人已下载