responsive Design Present

responsive Design Present


Responsive design howto <br />techniques et solutions <br />responsive design guideline

2 responsible responsiveness Mobile-first Responsive Web Design Darling, I don?t care if you are cold. If you knew how much optimization it had taken to look this good, you?d wear a bikini on the beach in winter, too. That?s a beautiful mobile site. But beauty is only skin deep.  nder the covers, it?s a different thing entirely. It may look like a mobile site, but it?s U still a desktop site in mobile clothing. If we want this site to be greased lightning on mobile, we need to start with mobile first. We?ll begin by dissecting the current site to find the desktop bones hiding in its mobile closet. We?ll clean house and start fresh with progressive enhancement, building from the basic content all the way to a desktop view. When we?re done, you?ll have a page that is optimized regardless of the screen size. this is a new chapter?? 43 not-so-splendid walrus Just when you thought it was time to celebrate? Mike called in a panic. As a reformed web developer, he normally resists the urge to tinker with his site, but he fell off the wagon and decided to make a few tweaks. He thinks he broke the Splendid Walrus site and needs help. Sorry, guys. Not sure what I did, but the Mike added pictures for all of his new brews to the On Tap Now Splendid Walrus site is page. He didn?t modify the code other than to add pictures, but now dog slow. now the page is loading very slowly on mobile phones. It?s so slow that customers have started complaining. Check out the On Tap Now page at http://hf-m 44?? Chapter 2 responsible responsiveness Is there really a problem? How do we know? Jim: Poor Mike. He knows just enough to get in trouble. Frank: Exactly. But in this case, I?m not so sure he did anything wrong. Mobile phones have slower networks and processors. Of course the page loads slowly. Jim: That makes sense, but it still seems slower than expected. Mike says that even on a WiFi network, it is unbearable. And he has a brand-new smartphone. Joe: Hmm?it sounds like we should at least look into it to see if there is something obvious slowing it down. Frank: How will we know what?s going on? It could just be the network or any number of things between the phone and the server. Joe: I?ve been using a plug-in for Firefox that gives you a grade on your page performance. We could use something like that. Jim: That sounds awesome. Frank: Can we install plug-ins on mobile browsers? Joe Frank The YSlow plug Jim Joe: Ugh, you?re right. There?s no way to install plug-ins performance bas-in gives you a grade for on my phone. Some of my favorite developer tools are constructed. G ed on how a web page is browser plug-ins. Without them, how do we know what?s Pet YSlow at this URL: really going on? every web devel erformance is something Jim: The other day, Kim was showing me how you can developers?shouoper?especially mobile web watch every request that is made on our WiFi network ld care about. through the network router?s log page. Could we look at something like that and watch what the phone does? Speaking of which, we?re going to spend a little time looking at performance. Don?t e worry. We?ll get to mobile-first Responsiv Frank: That?s a great idea. But instead, let?s use a proxy Web Design soon, and we promise all of this server. It is very similar to what Kim showed you, but it is designed for exactly this purpose. If we hook up the phone to a proxy server, we can see all of the web requests that performance stuff is related. the phone makes. you are here 4?? 45 wait, use a proxy Waitress, will you take my order please? A famous athlete is stricken with food poisoning the night before a big match against his archrival. The police suspect foul play and have assigned a detective. The detective quickly starts questioning the best witness: the waitress. The waitress took the food order, wrote down the request, and handed it to the cook. After the food was ready, the waitress brought the food out. The waitress saw everything. Most of the time when you?re on the Web, you?re talking directly to the cook. Nothing is between you and the web server for the page you?re visiting. But if we have a proxy server act like a waitress, it will record both what was ordered and delivered by the browser. Now we can be our own detectives and dig into what actually happened. Proxy server Mobile phone The Internet Web server You don?t need a fancy server. Your personal computer can act as a proxy server with the right software. Can I get a proxy to set up my proxy? If you do a lot of mobile work, you may find it worth your while to learn how to set up a proxy server. It is the best way to see what?s going on between the phone and server. Unfortunately, setting up a proxy server can be a tad difficult. Thankfully, some kind souls at Blaze, a mobile performance company, have set up a free service that is the next best thing to installing your own tool. 46?? Chapter 2 responsible responsiveness What to do when things aren?t blazing fast Blaze provides Mobitest?a free mobile performance test using real iPhone and Android phones. Mobitest is located at Blaze?s Mobitest works like a proxy server. You tell it what web page URL you want to test and what device you want to test with. Mobitest then puts your test request in a queue for that device. When the phone you requested is available, Blaze tracks all of the communication between its test phone and the web server so you can see what happened. There is even a fun feature that records a video of the page loading so you can see what someone using that phone would see. Test Drive Ready for some detective work? It?s time to figure out why the On Tap Now page is slow. 1 Test the On Tap Now page at The On Tap Now page is at 2 Look at the load time and page size. The load time tells you how long the page took to load on this phone during this test. The page size is the total size of all resources associated with the page including HTML, CSS, JavaScript, images, fonts, etc. 3 Try two different phones and compare speeds. Not only will the speed of networks vary, but the phones themselves may also vary in the speed at which they process and display pages. you are here 4?? 47 overweight walrus page Don?t let its looks fool you, that?s a BIG page Yikes! The test says the page is approximately 3 megabytes in size. That would be a pretty big page for a desktop browser. It?s a slow- In truth, it?s too big for desktop moving elephant on a mobile phone. too. Just because a screen is big doesn?t mean the connection is fast No wonder Mike?s customers complained about the page. It takes Performance matters everywhere. . over 10 seconds to load on a test iPhone. Blaze Mobitest results page using an iPhone Size of HTML Click to Load time and all resources see a larger can vary for the page version of widely the waterfall depending chart. network conditions. Blaze tests on WiFi. What is a waterfall chart? I looked at it, and it doesn?t tell me what?s making the page so big. Is the chart even useful? Waterfall charts are a common web performance report. The chart shows the files that the browser requested from the server to build the web page. The bars represent the length of time spent downloading a resource. The resources are listed in the order in which the browser requested them from the server. But don?t go chasing the waterfall on the Blaze report page. It doesn?t have the details we need for our detective work. We?re going to show you how to find a waterfall that is more useful. 48?? Chapter 2 responsible responsiveness Top part of th B There?s gold in ?em HAR hills Mobitest resulte laze s page. There is a nugget buried in the Blaze Mobitest results page behind the tiny View HAR file link. Click that link, and you will go to a new site called the HTTP Archive Viewer and see a more detailed waterfall than the test results page. This waterfall chart shows us every resource that the browser downloaded in much more detail than the picture of the waterfall on the Blaze report page. You?ll find the The preview tab cont ains a link next to the?View HAR file? Tw fo r th e page itter and waterfall chart ne rated Facebook links. we tested. It wa s ge HTTP Archive (HAR) Viewer from a HAR file. The HAR file ca n be used to make waterfat ll charts. HAR at Read more abou HAR stands for HTTP Archive. It is a file specification that provides a standard way to record what happens when a browser requests a web page Do you see any suspicious files being from a server. downloaded in the waterfall chart? you are here 4?? 49 bloated page pie charts 10,000-feet view: Show statistics The HAR waterfall charts show you the files that were downloaded, how the server responded, and the time it took to download. But before we dig into the waterfall chart itself, let?s take a look at the high?level statistics. Click the Show Statistics link on the HAR Viewer page to see a series of four pie charts. The chart that matters most to us is the second one, which breaks down the page by type of file. Hover your mouse over each file type to see its total file size. See the pie charts by clicking Show Statistics on the HAR Viewer page. Whoa! There are 35 image s; Eight JavaScript files for 2.4MB for images alo ne . this page. Total size of all JS is 351 KB. So that?s why the page is so slow. There?s nothing on this page that uses JavaScript, but it?s downloading eight JavaScript files. Plus the images are almost 2.4 MB in size. We need to figure out why the images and JavaScript are so big. 50?? Chapter 2 responsible responsiveness Find the drags on page speed Now it?s time to dig into that waterfall chart to find where the big images and JavaScript are coming from. Here?s a key to reading the chart. Waterfall chart on the HAR The web page requested. Each line shows a different file Viewer page Hover over it for a pull- requested to build the page. down menu with which you Size of the Hover to see the full URL. file downloaded Time required to can add more information download the file to the chart (e.g., the type of file). The type of request from the browser. Usually GET, but can be POST if it?s a form. Click the plus sign to get more details The HTTP response The bar graph shows when the file request about what the browser asked the code from the server. started and when the file completely server and how the server responded 200 means ?OK.? downloaded. Only a few files can be (aka the HTTP headers). downloaded at the same time. The amount of communication between the browser and the server can be overwhelming, but don?t worry. You just need to look for two things: which resources are the largest, and where is the JavaScript coming from? Review the waterfall chart for the On Tap Now page. Find the five largest files and examine them. For each file, answer: 1 What type of file is it? 2 What domain is the file coming from? 3 If the file is an image, what is its height and width? Hint: You may need to copy the image URL and open it in a new tab or download the image to find the dimensions. What does this information tell you about what you might need to do to make the page faster? you are here 4?? 51 exercise solution Did you find the problems with the page? Let?s review. 1 What type of file is it? You can determine the type of file by hovering over the filename to see the full URL and extension. You can also add a column containing the file type so you can scan the list quickly. Hover over the page UR 2 What domain is the file coming from? Click on the down arrowL. Now we?re getting somewhere. Check out where next to the URL to ad this big, 174.8 KB JavaScript file comes from. the file type column. d The large file isn?tfile the only suspicious ve here. These files ha strange names. Hover your mouse over the At 174.8 KB, this is th e largest name to see the full URL. file JavaScript file on th e pa ge. is a domain for Google Maps. The browser is downloading JavaScript for a map that isn?t displayed on the mobile view. Many of the mysterious files are related to Google Maps. 3 If the file is an image,? what is its height and width? 168 pixels high Find the images with the largest file size. Copy the URL and open them 750 pixels high in a new window. Without even looking at the height and width, you can tell that these images are far larger than the size they appear on 153 pixels wide a small screen. Scaled size used on iPhone Same file (121 KB) used for both despite the 682 pixels wide different sizes at which the image appears *Images are not to scale. 52?? Chapter 2 responsible responsiveness Where did that Google Maps JavaScript come from? When you view the On Tap Now page on a mobile phone, the page doesn?t contain a map. Why is that JavaScript downloaded? Let?s open the page in our desktop browser and investigate. Hey, there?s the map. Mike must have set it up so that it only shows up on wider screens. Hiding the map on the mobile makes some sense. It?s a bit big for a small screen. Older phones may not be able to handle the map?s complex JavaScript, and we?ve seen that the map has a lot of overhead. So how did Mike hide the map? One line to download them all Hey, there?s th The map is included in the page via an iframe. e elusive map! The iframe loads all of the components necessary to make the map. Look inside ontap.html to find this code. <iframe id="map" width="300" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src=""></iframe> This single iframe causes 47 files to be downloaded! Extremely long URL abbreviated taps.css Mike hid the map with CSS Mike figured out how we used media queries to @media screen and (max-width:480px) { modify the layout for mobile. He added in his own . e rules There are many mor CSS rule inside our media query. The rule Mike added sets the display for the iframe to none. . . in the CSS fi le . Unfortunately, while setting the display to none will prevent the map from showing up, it doesn?t #map {display:none;} prevent it from downloading. } The iframe has an id of map. This rule hides the Google Maps iframe by setting the display to none. you are here 4?? 53 optimize those images What?s with the big pictures? The images on this page need to be put on a diet. Let?s look at the waterfall to find the biggest images and see why they?re so big. The taps.jpg file is 440. 7 KB, making it . the largest file on the page But that huge file is the header image, and it isn?t even displayed on mobile. Right, but that doesn?t mean it?s not downloading. The taps.jpg image has been hidden from the page in the same way as Google Maps?the display property has been set to none in the CSS. But, as we saw with the map, setting display:none doesn?t stop the content from downloading. @media screen and (max-width:480px) { [Other CSS rules are here] .header {display:none;} This is taps.jpg. View the On Tap Now page in a desktop browser to see } where the image is used. Fluid images are huge images Another thing to notice from the waterfall is that the brew labels are all large files that range from 93 to 132 KB. The total size of the They?re desktop images scaled down to fit the screen 16 brew labels is near using the fluid-image technique we learned in Chapter 1. 2 MB. Finding a way ly So this isn?t a new issue, but when we only had one or to optimize these two images on the page, it wasn?t noticeable. But when images is key to making you put 16 brew labels on one page, suddenly the fluid the page faster. images are an anchor slowing the page down. 54?? Chapter 2 responsible responsiveness It looks mobile friendly, but it isn?t Jim: Well, that?s a bummer. I guess looks can be deceiving, eh? Frank: At least we can tell Mike he didn?t break the page. Joe: Yeah, any of us could have made the same mistake. The problems are really bad on this particular page, but I think the same issues exist on every page on the site. Frank: So what do we do? Build a whole separate site for the mobile version? Ditch Responsive Web Design? Joe: Let?s not get ahead of ourselves here. There?s got to be a way to make it work. We?re so close right now. Do the image and JavaScript problems have anything in common? Jim: It seems like all of the problems stem from the fact that we?re starting with desktop-appropriate content?images, maps, etc.?and then hiding that content. Frank: Exactly. We?ve got big files going to the browser by default and then CSS is being used to try to cover them up. But it seems that, if we?re not careful, the large files will still be downloaded by mobile devices. That?s not the ideal fallback behavior if something goes wrong. Joe: What if we flipped things around and sent the smallest files by default? Jim: Oh, interesting. That might work. Start with the mobile templates first and then add on content for desktop. Frank: What you?re describing sounds a lot like progressive Progressive enhancement enhancement. Joe: You?re right. We?ve been using progressive enhancement promotes building layered for years. The only difference now is that we?re starting from mobile and progressively enhancing the document to fit the web pages. At minimum, desktop. everyone can see and use Jim: It seems like it should work. Let?s try it out. the content. Those with more capable browsers get additional layers of style and interactivity that enhance the experience. you are here 4?? 55 mobile first; it?s only polite Mobile-first Responsive Web Design Mobile-first Responsive Web Design (RWD) is exactly what the name suggests: RWD techniques that start from a mobile template. Despite its simplicity, there is a lot of power that comes from this approach. es. ser featur ??Basic HTML of ad st for brow Very small screens ??Simple layout Progressive enhancement based on screen size and client features vanced (feature phones) ??Small images ??Limited CSS and JS e S to t t Use J r ??Add newer HTML5 features if supported ppo ??Simple layout s u Small screens (smartphones) ??Small images, but bigger than feature- siz e. phone size at es ??More CSS and JS layout and media Screen siz e d ict ??Because there is more room, Medium screens we can add optional content (tablets) like sidebars ??Multiple column layouts ??Larger images ??Add widescreen layouts ??Larger images Larger screens ??For TVs, optimize (desktops and TVs) navigation for use by people sitting 10 feet away who are using a remote control *These are just examples of enhancements. What you do depends on the project. 56?? Chapter 2 responsible responsiveness What is progressive enhancement? Progressive enhancement views web design in a series of layers. The first layer is the content. Combine that with semantic Behavior (JavaScript) markup to create structured content. If you stop right there, you have a document that nearly every browser in the world can read. Presentation (CSS) After you?ve got the basics out of the way, you add a presentation layer using CSS and a behavior layer using JavaScript. You never assume the browser supports those features, but if it does, visitors Structured content (HTML) get a better experience. For many years, web developers commonly built things that only worked on the most advanced browsers and tried to make sure the web page degraded gracefully on older browsers. Progressive Progressive enhancement is like a enhancement flips this practice around. layer cake. Mmm. Cake. Benefits of mobile-first design Mobile-first RWD isn?t that different from progressive enhancement. Recognizing this fact, many call it content-first design instead because content is the first layer of progressive Semantic Markup enhancement. Up Close Regardless of what you call it, starting from the most basic Semantic markup means HTML document not only reaches the most people, it also has tags and attributes that convey the beneficial side effects. meaning of the content. Mobile first is like a small-plate diet. Simply by eating on a For example, content surrounded by an smaller plate, you?re likely to eat less food. <h1> tag is more important on the page than content marked up with an <h2> The desktop home page is an all-you-can-eat buffet. All sorts of or a <p> tag. junk gets thrown on it. class and id attributes can also add Mobile is a small plate. You have to choose carefully and semantic meaning to documents if their prioritize your content. values are things like calendar and And once you?ve got a focused mobile site, you?re better prepared not presentation values like left or to ask the tough questions like whether or not the things that top. Many web developers use classes didn?t make the cut for mobile are really important enough to in a standard way called microformats to add back in for desktop. provide more semantic meaning. Learn more at Semantic markup doesn?t mean you completely avoid tags like <div> and <span> that don?t add meaning. Instead, you choose the right semantic tags and attributes for the content of a page whenever possible. you are here 4?? 57 current page structure check Let?s turn this web page around Because we?re already using RWD, making our page mobile first won?t take too long. Here is a short list of changes we?re going to make. We?ll explain w Make the HTML as simple as possible and swap the order of the CSS hy in a bit. so that the mobile version is first. Fix CSS background images so that only one file gets downloaded per image. Make sure display:none is being used appropriately. Supply different source files for <img> tags at different screen resolutions. Make sure the right size image is downloaded. Use JavaScript to add Google Maps to the page when the browser can support it and the document is wide enough to accommodate it. The current structure of the On Tap Now page Open up the ontap.html file for the Splendid Walrus site in the chapter2 directory. The file looks very similar to the document we built in Chapter 1: <div class="navigation">...</div> <div class="header">...</div> <h1>...</h1> Two columns <div id="visit" class="column">...</div> Instead of a <div> called instead of ?main,? Mike has created a new three <div id="ontap" class="column">...</div> column with the id of ?ontap.? <div class="footer">...</div> That <div> contains the list of current beers. Because we did a good job of creating a template with semantic markup, the document is clean and simple already. It looks like our main task to make the content mobile first will be removing the Google map. Because we?re going to need to reference the code later, let?s use HTML comments to prevent the iframe from being included in the page. Comment out the Google Maps--iframe by >. Find the iframe in the #visit <div>. surrounding it with <!-- and <!-- <iframe id="map" width="300" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src=""></iframe> --> 58?? Chapter 2 responsible responsiveness Am I on a new page or not? The On Tap Now page looks so similar to the home page. How can visitors tell they?re on a different page? Good catch. We have a problem with the order of the content. On the home page, it was fine if the first thing on the mobile view was the Visit Us information. But if the Visit Us content repeats on every page, visitors won?t be able to tell that the page has changed without scrolling down. We need to reorder the content so the On Tap Now info comes before the Visit Us content. Copy everything in the Do this! <div> with the visit id and paste it below the ontap <div>. <div class="navigation">...</div> <div class="header">...</div> <h1>...</h1> <div id="ontap" class="column">...</div> <div id="visit" class="column">...</div> <div class="footer">...</div> Is the Visit Us content essential on this page? Would it be better to move it to a separate page and link to it? Or maybe leave it out of the mobile page and add it using JavaScript if the page is rendered on a larger screen? you are here 4?? 59 content floating around the page Fix the content floats The change we made to the order of the content broke the layout in a desktop browser. The Visit Us section is at the bottom of the page. In Chapter 1, we mentioned how putting the right column before the main column was a trick to make it easier to handle floats for layouts. If you want a block to float next to something, you need to put it first in the source order. Don?t worry, though. There is a simple fix here. We?ve been floating the Visit Us content to the left of the On Tap Now content. Instead, we need to float the On Tap Now content to the right of the Visit Us content. Visit Us is floating Open taps.css and make the following two changes. beneath the beer labels. Before After @media screen and (min-width:481px) { @media screen and (min-width:481px) { .column { .column { margin: 10px 1.04166667% 0 0; margin: 10px 1.04166667% 0 0; } } #visit { #visit { width: 31.25%; Change this? ?to this. margin: 0 68.75% 0 0; float: left; } } #points { #points { width: 25%; width: 25%; float: right; float: right; } } #main { #main { margin: 10px 27.0833333% 0 26.0416667%; margin: 10px 27.0833333% 0 Using 67% 26.0416667%; } } Change this? #ontap { instead of #ontap { width: 67%; 68.75% gives us margin: 10px 0 0 32%; ?to this. float: right; a little wiggle margin: 10px 0 0 0; room for the columns. } } } } 60?? Chapter 2 responsible responsiveness Mobile-first media queries Now for a little housekeeping. In Chapter 1, we started with a desktop website Basic and made it mobile. We?re going to turn this around and start from the simplest styles content and build up to the desktop (and beyond). But first we have a confession. Mobile first is a little bit of a misnomer when it Small scr comes to the CSS. Before we apply any media queries for small screens, we?re ee n styles going to set all of the basic styles?for color, type, etc.?and then enhance them. There is a good reason for doing this. Many mobile browsers don?t understand Large scr media queries at all. So we need to make sure they at least get the basic ee n styles style rules. Put your CSS house in order CSS files are often like the kitchen junk drawer. It may start out organized and logical, but over time chaos takes over. To put mobile-first media queries in CSS cascade follows the place, you may need to untangle the basic style rules from the layout rules. Fortunately, the CSS we built in Chapter 1 is already in good shape. Most of the path from small screen to basic style rules are already at the beginning of the file, with the media queries large screen. adding the layout and formatting later in the document. All we need to do is put the mobile media query before the desktop query. Do this! /* Wider viewports/higher resolutions (e.g. desktop) */ @media screen and (min-width:481px) { [Desktop layout rules here] Move the mobile media queryry. block above the deskto p me dia que sure } By doing this, we?re making S is /* Mobile/lower-resolution devices */ the cascading eff ect of CS @media screen and (max-width:480px) { consistent with our mo bile -f irst [Mobile layout rules here] progressive enhancement approach. } Test Drive We?ve made quite a few changes to the page: ? Removed Google Maps ? Fixed the floats ? Reordered the markup ? Reordered the media queries We better check to make sure things still work. Load the page in a few desktop and mobile browsers to see how it looks. Be sure to check Internet Explorer. you are here 4?? 61 conditional comment lifelines Surprise! The page is broken in Internet Explorer Don?t tell us you didn?t see this coming the moment we hinted you might want to test the page in Internet Explorer (IE). Battling IE is a rite of passage for web developers. You?ve probably been scarred enough from previous battles that you knew there was an IE-sized monkey wrench awaiting us. So what?s the catch? IE doesn?t support media queries. Now before you toss the book aside and curse us for teaching something that doesn?t work in the world?s most popular browser, take a deep breath and relax. There are ways to work around IE?s (many) shortcomings. We?re being a little too harsh. IE9 and above do support media queries, so help is coming. Because IE 8 and below don?t sup media queries, IE isn?t gettin port CSS rules that create columns. g the Internet Explorer?s escape hatch: conditional comments Microsoft has provided a nice tool to help web developers target code specifically to Internet Explorer via conditional comments. browser is less than (lt) IE 9 and This tests to see if the(!I obile). We exclude Mobile IE that it isn?t IE Mobile e EM bile layout. IE9 and above See the full syntax for conditional because it should get th mo they don?t need the extra help. comments at understand media queries, so Look carefully. The <!--[if (lt IE 9)&(!IEMobile)]> HTML comment opens on the first <link rel="stylesheet" type="text/css" href="layout.css" media="all" /> line, but doesn?t <![endif]--> close until ?-->? is included on the final line. Other browsers If the conditions are met, IE will do whatever is in between the opening [if] will see this as a statement and the closing [endif]. The example shows a link to a CSS file, comment and ignore but it could be anything you would find in an HTML document. its content. 62?? Chapter 2 responsible responsiveness Use conditional comments with a media query You probably noticed that the conditional comment points to layout.css. Time to create that file. We?re going to grab some of the rules from the current stylesheet. We?ve called the new file layout.css because it will only be used for browsers that have enough screen real estate that multicolumn layouts make sense. 1 Create a blank text file called layout.css and copy the desktop rules into it. Make sure you copy everything between the beginning and end of the media query, but not the @media rule itself. taps.css After you copy them, remove the rules and the surrounding media query from taps.css. We?ll /* Wider viewports/higher resolutions reapply the rules to the HTML document next. (e.g. desktop) */ layout.css @media screen and (min-width:481px) { .column { .column { margin: 10px 1.04166667% 0 0; margin: 10px 1.04166667% 0 0; } } #visit { #visit { margin: 0 68.75% 0 0; margin: 0 68.75% 0 0; } } #points { Copy these #points { width: 25%; rules to width: 25%; your new float: right; file. float: right; } } #main { #main { margin: 10px 27.0833333% 0 margin: 10px 27.0833333% 0 26.0416667%; 26.0416667%; } } #ontap { #ontap { width: 67%; width: 67%; float: right; float: right; margin: 10px 0 0 0; margin: 10px 0 0 0; } } } you are here 4?? 63 conditional love 2 Add a link to the new stylesheet. For browsers that support media queries, we?re going to add a link to the new layout.css file if the screen size is wide enough. <link rel="stylesheet" type="text/css" href="taps.css" /> <link rel="stylesheet" type="text/css" href="layout.css" media="all and (min-width: 481px)" /> Add this link tag The 481px value for min-width was copied from the media query we This is the media query syntax to ontap.html. for link tags that you learned removed from taps.css. in Chapter 1. 3 Add the IE conditional comment. We?ve got it working for most desktop browsers. Now we just need to add the conditional comment we created earlier to finish up. <link rel="stylesheet" type="text/css" href="taps.css" /> <link rel="stylesheet" type="text/css" href="layout.css" media="all and (min-width: 481px)"> <!--[if (lt IE 9)&(!IEMobile)]> <link rel="stylesheet" type="text/css" href="layout.css" media="all" /> <![endif]--> The conditional comment repeats the line above it, ensuring that desktop IE sees our layout.css file. 4 Time to test again. Check the page in a browser that supports media queries and different versions of Internet Explorer. Looks good, huh? Even our persnicketyth old friend IE is sh ow ing e layout prop er ly no w. 64?? Chapter 2 responsible responsiveness Q: With super-fast 4G phones on the Q: You mentioned that setting up a Q: It seems like the order of content horizon, is performance really that big of proxy server might make sense. What do may often be different between desktop a deal? you recommend? and mobile. How do you handle this in A: more complex pages? Absolutely. Even 4G phones end up on the EDGE network occasionally (EDGE is A: There are many proxy servers, including some fantastic open source ones. A: Ah, you caught that, huh? Yes, this an older, slower network). Studies show that We happen to be fans of a commercial is one of the common challenges for slow sites decrease usage and directly affect product called Charles Proxy. Responsive Web Design. In the long run, Q: the bottom line. the Flexible Box Module (Flexbox) in CSS3 Q: The lack of plug-ins seems like a promises an easy way to reorder content in Why am I getting different results big deal. How do you get anything done stylesheets. Combine Flexbox with media from the Blaze Mobitest? without Firebug and Web Inspector? queries, and you can completely reorder pages as needed. Unfortunately, Flexbox A: There are many reasons why this can occur. Page download time will change A: It isn?t easy. First, a lot of your debugging work can be done in a desktop is still young and isn?t fully supported. So developers resort to JavaScript to reorder content or combine RWD with device with every test depending on network traffic. browser so long as you are careful to test on detection (see Chapter 5). Frankly, content Google Maps code is different for each real devices at some point in the process. ordering and image handling remain two of operating system and may change over time. There are also a lot of new tools that attempt the biggest challenges for RWD. The behavior of the phones will also change as new versions of the operating systems are released. For the book, we tested using to get around the plug-in limitations. The Mobile Perf Bookmarklet ( mw-perf) includes many performance tools. Q: Will the versions of IE that don?t Blaze?s iOS 4.3, Android 2.2, and Android support media queries see the responsive weinre ( and Opera design? Aren?t media queries necessary? 2.3 test devices. Dragonfly ( let Don?t worry too much about the variations in test results. What matters is the code and you run Web Inspector on your desktop and examine what is going on in the phone A: Internet Explorer will display the desktop version. It will still have the fluid images being downloaded unnecessarily. browser. grids and flexible images. But it won?t Q: By separating the stylesheet into Q: It doesn?t seem like much changed change based on any of the media query instructions. If media query support is two files, aren?t you making the site load when we switched to mobile-first media critical, there is an open source library more slowly? queries. Why bother? called Respond.js that fills in support for A: A: media queries for older IE versions. This is It is true that the number of HTTP For this page, there wasn?t a big a fairly intensive script, so be sure to test requests makes a big difference in the difference between a desktop-first CSS file extensively if you decide to implement it. download speed. So we shouldn?t recklessly and a mobile-first one. In our experience, add requests. In this case, we thought it however, this is the exception. With more made more sense to separate them so IE complex styles, you often want the wider could use the same file. rules to override some, but not all, of the styles set for smaller screens. Reordering the media queries ensures that the CSS cascading behavior is consistent with the goal of progressively enhancing the page as the screen gets wider. you are here 4?? 65 fix display:none with a media query How are we doing? We?ve got the basics in place and our CSS in order. What?s next on our list? Make the HTML as simple as possible and swap the order of the CSS so that the mobile version is first. Fix CSS background images so that only one file gets downloaded per image. Make sure display:none is being used appropriately. Supply different source files for <img> tags at different screen resolutions. Make sure the right size image is downloaded. Use JavaScript to add Google Maps to the page when the browser can support it and the document is wide enough to accommodate it. Play taps for the header image Our waterfall chart showed us that we had one large CSS background image that was being hidden with display:none. Despite the fact that the image never shows up on the page, the browser still downloads the image. So let?s make sure the image is only downloaded when it is Remember ou which downloardfriend, taps.jpg, needed. How do we do that? By putting it in a media query so it never shows up s on mobile but only gets downloaded if the screen is wider than 480 pixels. But instead of creating a whole new media query, put the CSS on the page? rules in layout.css, which is already being included in the page via a media query in the <link> tag. Copy these lines from .header { taps.css and add them background:URL('images/taps.jpg') repeat-x; to the end of layout.css. Delete these lines height: 300px; from taps.css } after you add them to layout.css. Test Drive Check the On Tap Now page using the Blaze Mobitest to make sure taps.jpg is no longer being downloaded. Try both iPhone and Android devices. You can use if your copy of the page is not on a public server. 66?? Chapter 2 responsible responsiveness It works on iPhone, but the image is still downloading on Android. Android appears to still be downloading taps.jpg. Blaze?s Mobitest says Android is still downloading the image, but it is a false report. Blaze had to modify its phones to make them work for remote testing. This causes some occasional odd behavior. When you use a stock Android phone, the taps.jpg image will not be downloaded. Going old school with image optimization Back in the early days of the Web, web developers spent a lot time worrying about image optimization. As bandwidth has increased, web developers stopped worrying about eking out every bit of performance from images. But mobile devices make image optimization paramount once again. We?d argue that imag It looks like we can make the taps.jpg image smaller with some basic web optimization has e image optimization. Changing the JPEG quality from 80 to 45 makes the always been paramount. image 78 KB instead of 440 KB, Faster connections ar and you have to look very closely to never a given, even fo e see any difference in image quality. destkop computers. r zation, For more on web image optimi ML see Chapter 5 of Head Fir HT st with CSS & XHTML. Images still not small enou Smush them further at gh? Copy the optimized version of taps.jpg from the extras folder into the images folder to replace the original, large We?re using Photoshop to optimize this file with a smaller version. photo for the Web, but you can use your favorite web image editor. you are here 4?? 67 scale images to the device One src to rule them all CSS images are just the beginning of our image woes. The <img> tag presents problems for every responsive design because there can only be one value for the src attribute regardless of screen size. So how do we deliver the right size image? labels on the On g There are 16 beer at use an <img>er ta Despite the need for multiple versions of this image depending on the Tap Now page th enson?s B ub bl . screen size, HTML only allows one value for the src. like this one for B <img src="brews_images/bensons_bubbler.jpg" alt="Benson's Bubbler"> It?s tempting to replace the value of the src attribute using JavaScript. Unfortunately, most browsers look ahead at the HTML document and preload CSS can?t be used to images before the JavaScript has been fully evaluated. This often means override the value of the one size file downloads before the JavaScript changes the src, resulting in src attribute, either. duplicate downloads and causing the browser to reflow the page layout. A responsive image server to the rescue If the browser can?t ask the server for the right image, the server will just have The image resizing service to figure it out for itself. That?s what Src attempts to do. formerly known as TinySR C We can use Src to deliver the best-sized image for every device. the full URL of Set the first part of the src to Replace with your domain and After the slash, addto path to the images. the image you want have resized. <img src="[DOMAIN]/[PATH]/brews_images/bensons_ bubbler.jpg" alt="Benson's Bubbler"> Src will resize the image to fit the size of the device screen. For example, if an iPhone Src visits the site, the image will be constrained to its only shrinks screen size of 320 by 480 pixels. Do this! images. It doesn?t make them bigger. Enlarging images results in Update all of the brew label images in the poor quality. It is better to find ontap.html document to use Src. a higher-quality source image. 68?? Chapter 2 responsible responsiveness How Src works Src works like magic. You request an image from an iPhone, it gives you an iPhone-sized image. Using a feature phone? No problem? Src will give you a tiny image. Sitting at your desktop? Here?s the full image. How does Src know what size image to deliver? It uses the browser?s user- agent string?an identifier that every browser provides?to look up the device in a What?s a user-agent strin ing? big database. The database contains information about thousands of devices. One We?ll take a closer loo k the of the things these device databases track is the size of the screen. next chapter. Once Src knows the screen size, it goes to work scaling the image to the maximum width of the device. It stores the image it created in a cache for 30 minutes so subsequent requests for the image at that size will be even faster. If you need Senc provide a Src to No great solutions for <img> tags it can do that fo image size, well. See how at ht r you as Using Src has drawbacks. It relies on device detection, which can senchasrc. tp:// occasionally get things wrong (as we will discuss in more detail in Chapter 5). It also requires you to route all your images through a third party. The reality is that there are currently no great solutions for how to handle different image sources for different screen sizes. But watch this space closely, because a lot Why is the <img> tag so of people are trying to find a better solution. difficult? Read more in this series on responsive image One final tweak: optimized beer label images s: As with the taps.jpg image, we can reduce the file size of the beer label images by saving them at a slightly lower JPEG quality level. Don?t worry, we?ve optimized them for you. Find them in the extras/labels-optimized directory. Copy the optimized images into the brew_images folder, replacing any existing image files. Test Drive We should have an efficient, fast, mobile-optimized web page now. Test it using to see how we did. Select the option to have Blaze run three tests on the phone to get an average. Compare the total file size and download time of the new page to the original page. If your pages are not publicly accessible, you can test using you are here 4?? 69 performance, optimized That?s a blazing-fast mobile web page Our diet plan worked! The On Tap Now page is 87% slimmer than it was before. iPhone download time has gone from almost 12 seconds to under 3 seconds. Before Can you say ?Bloated, S?L?O?W loading page?? After The On Tap Now page?s post- optimization results. Much better. Mike is going to love how fast the site is on a mobile phone now. Web performance optimization is a growing field with many more ways to make pages faster. What other performance improvements could we make to this page? 70?? Chapter 2 responsible responsiveness Q: Why do browsers download CSS images that are Q: What about other media? Do video and audio suffer never used? from the same problems? A: The browser usually can?t know for certain that an image isn?t going to be used. It could be an image that shows up A: In a word: yes. The HTML5 video and audio formats are a little better because they allow you to define fallback versions when some JavaScript or CSS activity triggers it. The browser of the media in different file formats. If your browser doesn?t downloads the images in advance so people don?t have to wait support the first option provided, it will look at the second one. if an activity suddenly triggers an image to be displayed. But while better, this approach does nothing to address Q: OK, so why don?t they download images that are network speed or resolution. Someone using a mobile phone on a wireless network probably doesn?t need an HD-quality within media queries? movie. By contrast, Apple?s QuickTime video offers a movie A: Originally, browsers downloaded them as well. Browser reference format that delivers movies based on Internet connection speed. Q: makers have seen how developers are using media queries and are adjusting browser behavior accordingly. All of this Is it just me, or are there a lot of unknowns and is fairly new, which is why some browsers still download problems related to Responsive Web Design? resources inside a media query that doesn?t apply. Q: Is it safe to route our images through A: There are definitely challenges. As with any new technique, people are still trying to figure out what works and Src? It makes me nervous. what doesn?t. RWD is bleeding edge. That?s why we?re covering A: Being cautious is reasonable. Any time you integrate a third-party service into a critical part of your site, you?re going a lot of techniques in this book. It?s likely you?ll need to combine techniques to deliver the best experience for your project. Despite the challenges, the promise of RWD inspires many to be impacted if that service goes down. people to strive to build more complete solutions. Things are Sencha has said it is committed to providing this service and moving quickly when it comes to RWD. that it will remain free. At the same time, you can be sure that if a tremendously large site started using it, Sencha would need to be compensated or it wouldn?t be able to run the service. If you don?t like Src, you could build a similar service using the device detection tools we teach in Chapter 5. Q: Are there alternatives to Src? Are there solutions to the <img> tag problem that are client side only? A: There are many different ways to handle <img> tags in responsive designs. A lot of work is currently underway to find a solution that doesn?t require device detection. There are compromises with every solution, including the one we?re using for this project. You can find an extensive review of the techniques at you are here 4?? 71 to zoom or not to zoom? Zoom, zoom, pow? Sorry, guys! I hate to spring a new requirement on you in the middle of your work, but one of my best customers has trouble seeing small text and is complaining that she can?t zoom the page. Can you fix it? Remember that viewport <meta> tag from Chapter 1? Time to look at it more closely. The viewport <meta> tag tells the browser the intended dimensions and scaling (aka zoom level) for a page. It also contains controls that can prevent users from being able to change the size of the page. Zoom in on the viewport <meta> tag You?ll find the viewport <meta> tag in the <head> of the ontap.html document. The syntax is pretty simple. ains a The content attribute cont instructions comma-separated list of of the Width of the viewport. Can be set in for the browser. See all/metaviewport. pixels or can be set to ?device-width What type of options at http :// bit .ly which tells the browser to match the ,? <meta> tag is this? viewport to the device resolution. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /> Sets the initial scale (or zoom Declares a limit on The maximum?scale level) of the page. Setting it to 1 how much the page is what is preventing means that the document should be can be scaled up. the users from displayed at its normal scale. There is also a similar zooming the page. minimum?scale setting. 72?? Chapter 2 responsible responsiveness The right to zoom? It seems like being able to zoom is important for accessibility. Why would anyone ever turn it off? It can make a difference for accessibility. Some web developers have gone so far as to declare that zooming on mobile is a fundamental human right. We wouldn?t necessarily go that far, but zooming is important, and it should be considered carefully before it is disabled. As for why designers disable scaling, there are a few reasons. If the page is using complex touch gestures, disabling zoom makes it easier for people to swipe successfully. There is also a bug in iOS that causes the zoom level to change when the device is rotated into landscape mode. The bug zooms the page in, causing the right side of the page to get cut off. When you rotate an iOS vic Turn zooming back on bug causes the page to nodelon e, a fit in the viewport, cutting r ge To turn zooming back on, we need to the right side of the contenoff remove the maximum-scale setting t. from the viewport <meta> tag. Do this! Edit the viewport <meta> tag and remove ?maximum-scale=1.? <meta name="viewport" content="width=device-width, initial-scale=1" /> After you turn zooming back on, rotate an iPhone or iPod Touch to Make sure you remove the extra see the iOS zooming bug in action. comma after ?initial-scale=1.? you are here 4?? 73 map out the final step Back to our regularly scheduled project With our emergency viewport adventure out of the way, let?s take a look at our progress. Our fast mobile page puts us very close to a mobile-first RWD. All that?s left to do is add the map back in if the screen is big enough. Make the HTML as simple as possible and swap the order of the CSS so that the mobile version is first. Fix CSS background images so that only one file gets downloaded per image. Make sure display:none is being used appropriately. Supply different source files for <img> tags at different screen resolutions. Make sure the right size image is downloaded. Use JavaScript to add Google Maps to the page when the browser can support it and the document is wide enough to accommodate it. Add the map back using JavaScript The only remaining item is to add the map back if the browser window is wide enough. We?ve already seen that, if we hide and show the map using CSS, the resources for the map will still get downloaded. So we?re going to need to use JavaScript to add the map when appropriate. Think of it as a JavaScript version of the media queries we know and love. Grab that Google Maps iframe code that we set aside earlier. We?re going to need to put that back into the page in order to show the map. Let?s take a closer look at the iframe code. snippet that Remember this iframeWe?re going to use we commented out? it into the page. JavaScript to insert <!-- <iframe id="map" width="300" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src=""></iframe> --> 74?? Chapter 2 responsible responsiveness On second thought, a map would be useful Location. Location. Location. The old saying takes on new meaning when it comes to mobile phones. Because many phones can tell where you are via GPS and other forms of triangulation, using location to provide more relevant content is common. Mike hid the map on mobile because it was too big. Now that we?ve seen how many files it downloads, it makes sense to keep the map hidden. But that doesn?t mean a map wouldn?t be nice. So instead of embedding a map on narrow screens, let?s link to the map. Add a link to the map To link to the map, we?ll need a <div> that our JavaScript can reference. The <div> will contain a <p> tag with a link to the map. Why do you think we need to order it that way? Do this! ript go in g to ne ed a co ntainer for the JavaSc We?re add a <div> here. to reference, so we?ll The id on the <p> <div id="mapcontainer"> tag will allow us to <p id="maplink"> insert the iframe above the link for e <a href="">View Google Map</a> wider screens. Mor </p> on this soon. </div> <!-- Add the new <iframe id="map" width="300" height="300" frameborder="0" <div> above the scrolling="no" marginheight="0" marginwidth="0" commented-out src=""></iframe> iframe code. --> you are here 4?? 75 it?s kinda like a media query Build a pseudo-media query in JavaScript This variable is for the id of the element we want to add the map to. Let?s take a look at the JavaScript code we?re going to use to insert the We?re using a variable to make the iframe into the page. The code acts like a very simple media query. Sets the breakpoint <div> easier to change in the future. variable to 481 pixels. The breakpoint is the <script type="text/javascript"> width at which the map will be added to var breakpoint = 481, the page. id = 'mapcontainer', Checks to see viewportWidth = window.innerWidth; if the window if (viewportWidth > breakpoint) { viewport is larger var mapElement = document.createElement('iframe'); than the breakpoint = 'map'; Adds a new iframe mapElement.width = '300'; element and assigns it to These lines add all mapElement.height = '300'; the mapElement variable of the attributes mapElement.frameborder = '0'; to our new iframe mapElement.scrolling = 'no'; element. The mapElement.marginheight = '0'; The URL attributes and their mapElement.marginwidth = '0'; Google Maps values were copied provides is from the Google mapElement.src = ' ugly. You Maps iframe snippet. urce=s_q&hl=en&geocode=&q=334+NW+11th+Ave,+Portland,+O R+97209&aq=&sll=37.0625,-95.677068&sspn=58.164117,80.3 probably 32031&vpsrc=0&ie=UTF8&hq=&hnear=334+NW+11th+Ave,+Portl don?t want This final step and,+Oregon+97209&t=m&ll=45.525472,-122.68218&spn=0.01 to retype adds the iframe 804,0.025749&z=14&output=embed'; it. Find a (mapElement) into copy of the mapcontainer document.getElementById(id).insertBefore(mapElement, maplink); this code in <div> (id) before extras/map.js. the paragraph } containing the link </script> (maplink). Remove the commented-out iframe code We no longer need the original iframe code, so delete it from the HTML document. <!-- Delete these lines! <iframe id="map" width="300" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src=""></iframe> --> 76?? Chapter 2 responsible responsiveness Add the JavaScript to the On Tap Now page Now we need to add the JavaScript to the page. Because the map is a nice-to-have feature and not essential, we?re going to make it one of the last things the browser adds to the page. Open ontap.html and find the bottom of the HTML document. <div class="footer"> <p>See you soon! Love, The Splendid Walrus</p> We?re going to add our </div> JavaScript as the very last thing on the page before the [INSERT SCRIPT HERE] closing </body> tag. </body> </html> Putting nonessential JavaScript at the bottom of the page is a great way to make a page load faster. The browser will parse all of the HTML and CSS before it gets to the JavaScript. Our visitors will have a usable page more quickly and won?t be stuck waiting for the map code to load. Time to put our work to the test. Grab ontap.html and answer the following: 1 Does the JavaScript get downloaded on mobile phones? Load the page on iPhone and Android using Check the waterfall chart to see if the Google Maps code is downloading. If your web page isn?t on a public network, you can use to test. 2 Does the map show up on larger screens? Open the On Tap Now page in your favorite desktop browser. Does the map show up when the window is wider than 480 pixels? 3 How does the map fit into the responsive design? Try adjusting the size of your browser window. Does the map scale like the rest of the design? Are there any problems with the map? you are here 4?? 77 is the map responsive? How?s it looking? Any problems? 1 Does the JavaScript get downloaded on mobile phones? Check the page using an iPhone on the Blaze Mobitest service. Make your way to the detailed waterfall chart by clicking the HAR file link on the results page to see all of the files downloaded. The map files are not getting downloaded. Perfect. Now what about Android? Blaze says the JavaScript still downloads, but it is another false report. We mentioned that Blaze had to modify its phones to make them work for remote testing. One odd by-product of this modification is that JavaScript running on its test phones reports the screen width as much wider (800 pixels!) than what unmodified phones do. You?ll have to take our word for it that the JavaScript works and the map code isn?t downloading on Android, either. Look Ma, no Google Maps downloads. 2 Does the map show up on larger screens? Yep. The map looks great in our desktop browser. The map shows up in Chrome, which means our JavaScript is working. 3 How does the map fit into the responsive design? Uh oh. We?ve got some problems here. The map doesn?t scale like the rest of the responsive design. Not only that, but there are some screen widths where the map overlaps the beer labels. Yikes. When the browser window narrows, the map overlaps the beer labels. Why isn?t the map scaling like the images on the page? 78?? Chapter 2 responsible responsiveness These widgets aren?t responsive The iframe code for Google Maps isn?t designed to be fluid. It hardcodes the width to 300 pixels. I bet if we change the iframe to use CSS, we can make it fluid. Responsive Web Design is so new that widgets like Google Maps are unlikely to be fluid by default. When companies provide widgets to embed in other web pages, they do everything they can to make sure the widget will work regardless of the page layout. That often means hardcoding things like height and width in the HTML itself. Dealing with poorly built third-party widgets is a problem for nearly every mobile site. Responsive designs have an additional requirement that widgets be fluid. Width and height are fixed, which prevents the map from scaling. <iframe id="map" width="300" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src=""></iframe> Many of the attributes on this iframe could be moved to CSS. Ideally, our HTML would only contain the content and markup. It wouldn?t contain any presentation information. Which CSS properties map to the attributes used in the iframe? you are here 4?? 79 use css for presentation Move iframe attributes to CSS equivalents Let?s move as many of the iframe?s attributes to CSS as possible and make them fluid while we?re at it. First, we need to create a list of attributes we want to move to CSS by identifying which attributes are for presentation and which are content or metadata. Presentatio Presentation Metadata n Presentation Presentation <iframe id="map" width="300" height="300" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src=""></iframe> Presentation Presentation Content All those presentation attributes belong in the CSS. Match styles to attributes Some of the attributes share the same name with their CSS comrades. We don?t have to look hard to find the CSS version of Do this! width and height. Others, like frameborder, are obscure attributes. Fortunately, the CSS counterparts are still fairly straightforward. Add these rules to Our new CSS rules layout.css. h e ifr a m e attributes for the map iframe T To make the iframe <iframe fluid, we?re changing id="map" from a set number #map { of pixels to a width="300" width:100%; percentage like we height="300" height:100%; learned in Chapter 1. frameborder="0" border:none; scrolling="no" overflow:hidden; marginheight="0" In CSS, scrolling is margin:0; controlled by the marginwidth="0" } overflow property. This src="http://maps. says we want to hide any"> extra content instead </iframe> of adding scroll bars. It accomplishes the same thing as scrolling = ?no?. 80?? Chapter 2 responsible responsiveness Remove attributes from the JavaScript Now that we?ve got CSS doing the heavy lifting, let?s modify our JavaScript so the presentation attributes aren?t set. Remove the Find the JavaScript at lines that add the presentation attributes that we identified. the bottom of ontap.html. <script type="text/JavaScript"> var breakpoint = 481, id = 'mapcontainer', viewportWidth = window.innerWidth; if (viewportWidth > breakpoint) { var mapElement = document.createElement('iframe'); = 'map'; mapElement.width = '300'; mapElement.height = '300'; Delete these mapElement.frameborder = '0'; he lines from t . mapElement.scrolling = 'no'; JavaSc rip t mapElement.marginheight = '0'; mapElement.marginwidth = '0'; mapElement.src = ' urce=s_q&hl=en&geocode=&q=334+NW+11th+Ave,+Portland,+O R+97209&aq=&sll=37.0625,-95.677068&sspn=58.164117,80.3 32031&vpsrc=0&ie=UTF8&hq=&hnear=334+NW+11th+Ave,+Portl and,+Oregon+97209&t=m&ll=45.525472,-122.68218&spn=0.01 804,0.025749&z=14&output=embed'; document.getElementById(id).insertBefore(mapElement, maplink); } </script> Test Drive Save layout.css and ontap.html. Load the On Tap Now page in Safari. You can use if it?s more convenient. How does the map look? you are here 4?? 81 map misbehavior No one should have trouble finding the pub now The map got a little full of itself, didn?t it? It nearly took over the whole left column. Soon it will start singing, ?I?m the map, I?m the map? to get our attention?unless we tame it. If you make the window narrow, you can begin to see why the map might be trying to get our attention. The map gets squeezed until it These screenshots are from turns into a thin, tall strip that is completely unusable. Safari. Other browsers behave differently. The map isn?t doi We still want the map to scale, but we need to set some boundaries on what we want in any of them. ng how far it scales in each direction. 1 The height of the map is too big. Setting the height to 100% makes the map longer than the tallest image on the page. Let?s keep the map a little more under control by setting the height to 400px. Add this line to the #map CSS rule. height: 400px; 2 Hey look, the map is wearing skinny jeans. When the window gets narrow, the map gets so thin that most of the information cannot be seen. We need to set a minimum width so that the map doesn?t go beanpole on us. After adding the two new lines, your #map rule in #map { layout.css should look like this. width:100%; height:400px; border:none; overflow:hidden; margin:0; min-width: 200px; } 82?? Chapter 2 responsible responsiveness The map overlap is back I thought the whole reason for making the iframe fluid was to get rid of the overlap. We?ve got everything in CSS now, but the map is still covering up the beer labels when you make the browser window narrow. Moving the iframe presentation attributes into CSS was the first step. Now we need to take a fresh look at our media queries. In Chapter 1, we used media queries to switch the layout at 480 pixels. We determined that width based on the width of popular smartphones. What we?re seeing with the map is that we need to look at the content of the page when we make decisions about where to apply media queries. The map is cove again when the ring up the bee window is narr r labels ow. you are here 4?? 83 become one with your content Let the content be your guide There?s a problem with using 480 pixels as our breakpoint for the media query. Not every phone has the same width. And even if a majority of them do today, who?s to say that 540 pixels won?t be the most common size in the future? A better approach is to let your content be the guide on when to make changes to the layout. We?re not asking you to commune with your content until it starts to speak to you. But if you adjust the size of your browser window until things don?t look right, the content will tell you a lot. Maybe images are getting too small. Maybe the columns are too narrow. When those things happen, that?s where you need a breakpoint. Then you can craft a media query to change the presentation at that breakpoint. We shouldn?t pay so much attention to typical mobile and desktop screen sizes. When the content breaks the layout, it is telling us to adjust our media queries and JavaScript. 84?? Chapter 2 responsible responsiveness Time to bend and stretch that browser We need to put our content through its paces by making the page as big and as small as we can while watching for when the layout breaks. But before we do that, we need some way of knowing how big the screen is when something looks wrong on the page. The easiest way to do this is to install a bookmarklet that will show you the window size. A bookmarklet is a stored in a browser lit tle bit of JavaScript bookmark. Install the bookmarklet in your browser Go to and drag the link labeled Window Size into your bookmarks toolbar to create the bookmarklet. Click the bookmarklet to activate it. Resize your browser and watch the numbers change in the upper-left corner of the browser window. click The Window Size bookmark in ndow Size When you click the With ds e size of Safari?s bookmark bar. bookmarklet, it ad per-left the window in the up corner. Optional: Install an extension There is an extension for Google Chrome that not only will show the window size, but will also resize your window to match common screen resolutions. You can get it at The Web Developer Toolkit ( will display page size in the title bar along with a bunch of other useful tools. It works in Firefox and Chrome. Load the On Tap Now page in the browser with the Window Size bookmarklet (or a browser extension). Activate the bookmarklet. Resize the browser. Write down the width of the browser when the layout breaks or the content looks odd. you are here 4?? 85 sharpen solution Let?s review some of the trouble spots that show up when you resize the browser. 610 pixels: Beer labels touch the map. At around 610 pixels, the labels touch the map. If we?re going to create a new breakpoint to address this problem, we?ll need to do it before they touch. This means instead of using 610, we?ll use 640 pixels as the breakpoint. Where?s t whitespacehe gone? 1,200 pixels: Huge beer labels. As the browser gets wider, the beer labels become ridiculously big. Where they become too big is an aesthetic judgment. For our tastes, they start getting too big when the browser is 1,200 pixels wide. Did you see other problems as you resized the browser? How significant do you think a problem needs to be before it makes sense to address it with an additional media query? 86?? Chapter 2 responsible responsiveness Breakpoints to the rescue All in all, not too bad. Just a couple of small tweaks to the CSS should do it. Shrink the humongous beer labels There are currently three beer labels in each row. When the page gets wider, there is room for four beer labels per row. This change only happens if the window is bigger than 1,200 pixels. Create a media query for windows wider than 1,200 pixels that changes the beer labels to four across the page. @media screen and (min-width:1201px) { Setting the width of the list item (li) .taplist li { containing the beer labels to 25% will width: 25%; Add these rules put four labels on each row. to layout.css } } Going to one column sooner It?s common to make images smaller Even if the beer labels didn?t overlap with the map, the proportionally as screens get wider. layout is getting very crowded at 640 pixels. Instead of adding a new breakpoint to address the overlap, we can move our existing media query from 480 pixels Our HTML, JavaScript, and 480 pixels, so we?ll need CSS all reference to 640 pixels. to update all three. Making this change will convert the layout to a single column and hide the map. This has the added benefit of applying the single-column layout to phones bigger than 480 pixels. ontap.html <link rel="stylesheet" type="text/css" href="layout.css" <script type="text/ media="all and min-width: 641px)"> javascript"> var breakpoint = 641, Set min-width Set breakpoint ... to 641px. in JavaScript </script> to 641px. taps.css /* Mobile/lower-resolution devices */ Set max-width @media screen and (max-width:640px) to 640px. { you are here 4?? 87 slimline, responsive?it?s a whole new walrus Widescreen view with four beer labels per row You guys rock! The page is fast and looks great. Drinks are on the house. Narrower views go to one column and hide the map. Lightweight and fast on mobile You can use Our mobile-first responsive design is complete to run your own speed tests. 8/ontap.html Make the HTML as simple as possible and swap the order of the CSS so that the mobile version is first. Fix CSS background images so that only one file gets downloaded per image. Make sure display:none is being used appropriately. Supply different source files for <img> tags at different screen resolutions. Make sure the right size image is downloaded. Use JavaScript to add Google Maps to the page when the browser can support it and the document is wide enough to accommodate it. 88?? Chapter 2 responsible responsiveness Q: What exactly is a viewport? Q: What are breakpoints? Q: Why does the overlap with the map A: A: occur in the first place? Imagine taking a sheet of cardboard and cutting out a rectangle in the middle of it. Lay that rectangle over your monitor so Breakpoints are just a fancy way of describing the resolution at which a designer decides to change the layout of a page. This A: Because the map is an element that doesn?t scale with the browser window. you can only see the portion of the web page is usually done via media queries checking When the window is small, the browser can?t that shows through the rectangle. That?s to see if a page is narrower or wider than a scale the map any smaller, so the left column what a viewport does for web pages. certain number of pixels. ends up overlapping the right column. Q: So the viewport <meta> tag A complex responsive design may have multiple breakpoints, including some that Q: Doesn?t adding a min-width tells the browser what size to make the make wholesale changes to the layout as to the map break the responsive design viewport? well as some minor breakpoints that only by creating an element that doesn?t scale A: make a few targeted tweaks to fix minor with the browser window? A: Exactly. By default, iOS sets the layout issues. viewport to 980 pixels. If you?ve optimized your page for smaller screens, setting the <meta?viewport> tag lets the Q: I don?t want to prevent people Technically, yes. It seems like a decent solution here because we?ve modified the media queries to address overlapping from zooming, but that iOS bug is pretty browser know to set the viewport accordingly. heinous. Is there any way to enable content. Another option would have been to zooming and not have a broken page? use media queries to adjust the dimensions of the map and proportions of the columns. A: You can find a JavaScript workaround at Adding media queries to an existing desktop site may Mobile-first RWD is another form of progressive make it look good on mobile, but doesn?t mean that it is enhancement that uses screen size to determine how mobile optimized. to enhance web pages. Because most mobile browsers don?t support plug-ins, Designing for mobile first forces you to focus on what there are fewer tools to assist mobile web developers. really matters, thus helping you remove cruft from Using a proxy server or a testing solution like Blaze pages. Mobitest can help you see what is actually getting Internet Explorer 8 and below do not support media downloaded by a mobile browser. queries. Conditional comments are a workaround. HTTP archive files and waterfall charts are essential JavaScript can augment media queries by testing for performance tools. screen size and adding content when appropriate. Mobile-first Responsive Web Design helps optimize Instead of designing breakpoints based on the typical web pages by making sure that smaller resources are screen resolutions, let the content dictate the downloaded by default. resolutions at which you need to modify the layout. you are here 4?? 89


Envoyer le lien par email
#responsive design  #web mobile  #html5  #mediaqueries  #mobile web develop 

Licence Publique Gnrale GNU

Web Design 

Partagé par  ced


Source:Non communique