HTML5 and CSS3 Responsive Web Design Cookbook

dycg

贡献于2013-10-01

字数:0 关键词: 前端技术 CSS HTML

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 www.packtpub.com Cover Image by Duraid Fatouhi (duraidfatouhi@yahoo.com) 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 CBSNews.com, 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 (http://jackdrawsanything.com/) 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 www.qafe.com 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. www.PacktPub.com Support files, eBooks, discount offers and more You might want to visit www.PacktPub.com 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 www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. http://PacktLib.PacktPub.com 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 www.PacktPub.com, 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…

”robots

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 feedback@packtpub.com, 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 www.packtpub.com/authors. Customer support Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase. Preface 4 Downloading the example code You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you. 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 http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded 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 http://www.packtpub.com/support. 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 copyright@packtpub.com 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 questions@packtpub.com 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 http://www.gimp.org 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 http://www.lipsum.com 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 http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub. com/support and register to have the files e-mailed directly to you. 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 http://www.html.it/ 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 (http://lipsum.com/). 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 (http://ipsum.com). 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 http://www.gimp.org. 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 http://www.w3.org, 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 (http://lipsum.com) 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, http://lipsum.com. 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 http://lipsum.com.

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

    Comments

    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 http://www.w3.org/TR/css3-mediaqueries/. 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 http://lipsum.com 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

    really?

    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

    下载文档,方便阅读与编辑

    文档的实际排版效果,会与网站的显示效果略有不同!!

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

    下载文档

    相关文档