Web Design Blueprints - Benjamin LaGrone - E-Book

Web Design Blueprints E-Book

Benjamin LaGrone

0,0
34,79 €

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

Mehr erfahren.
Beschreibung

Build websites and applications using the latest techniques in modern web development

About This Book

  • Create amazing modern day applications that run seamlessly across multiple platforms
  • Implement multiple methodologies by creating different apps with dynamic features
  • This unique project-based guide will help you build your own websites efficiently

Who This Book Is For

This book is a must-have for web developers who want to stay on top of the latest trends in web app and site development. If you are a web developer who is already familiar with HTML, CSS, and functional JavaScript, and you want to learn the latest trends in web development, this is the book for you.

What You Will Learn

  • Find out how to create responsive websites
  • Create websites using the principals of Flat design
  • Create deep-dive sites using parallax scrolling
  • Discover how to use Ajax in single-page applications
  • Create responsive navigation with CSS and JavaScript
  • Create responsive padding with the box model property

In Detail

The book delivers simple instructions on how to design and build modern Web using the latest trends in web development. You will learn how to design responsive websites, created with modern Flat User Interface design patterns, build deep-scrolling websites with parallax 3D effects, and roll-your-own single-page applications. Finally, you'll work through an awesome chapter that combines them all.

Each chapter features actual lines of code that you can apply right away.

Style and Approach

Using real-world examples, Web Design Blueprints presents practical how-to projects for site enhancements, with a light-hearted, easy-to-understand tone. This book has individual projects that cumulate until you finally build a super-project at the end, using all the skills learned

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

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 276

Veröffentlichungsjahr: 2016

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



Table of Contents

Web Design Blueprints
Credits
About the Author
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
1. Responsive Web Design
Introduction to responsive web design
Getting familiar with the basics
Using the inspector
Understanding the viewport meta tag
Learning about the viewport meta tag by example
Viewing your work on the tag
Fixing the problem by adding the proper meta tag
Further explanation of the viewport meta tag
Understanding and changing the user agent string
Using the user agent string for testing
How to change the user agent string in Chrome
What next?
Using media queries for responsive design
Some background information
A small example
A better example
Adding style
Viewing your example
Adding complexity to your stylesheet
Adding more media queries
More complicated examples
Working with responsive media
Creating responsive images with srcset
How things have changed
A brand-new solution
Enough theory, let's do something
Layout basics
Making the img element responsive
Viewing your responsive image
Creating responsive images with CSS
Getting started coding
Responsive style
Above and beyond
Calculating the responsive image size
Adding responsive video to your site
Working with two use cases
Use case #1 – self-hosted video
Use case #2 – embedded through the iframe element
Responsive video CSS
Modifying the layout
Viewing the example
Communicating with responsive typography
A good solution for responsive typography
Working with an example
Create the typography's CSS
Finished!
Building responsive layouts
Creating responsive padding with the box model property
A real-world example
Applying the box model property
Finished!
Going further
Viewing your example
Adding more complexity
Finished! Now view your work
Creating responsive navigation with CSS and JavaScript
Jump into an example
Creating the responsive CSS with media queries
Your first version is complete
Going further
Adding interaction
Finally, the interaction function
Viewing your interactive responsive navigation
Summary
2. Flat UI
A brief history of flat design
Flat UI color
Sample color swatches for flat UI
The vivid color swatch
The retro color swatch
The monotone color swatch
Creating a color swatch for your project
Creating a flat UI layout
Adding content
Creating a working JavaScript clock
Adding textual content
Let's talk about the weather, travel, and the stock market
Flat UI typography
Adding webfonts
Adding flat UI elements
Flat UI CSS cleanup
Creating universal classes
Fixing time
Fixing the news and tasks elements CSS
Adding CSS for the weather section
Creating more universal classes
Final cleanup of the landscape orientation
Final cleanup of the portrait orientation
Summary
3. Parallax Scrolling
Starting off
The HTML markup
Color classes
Using SVG font icons
Getting the fonts
That's no moon!
OMG, it's full of stars!
Clouds, birds, and airplanes
The rocket
Terra firma
Next up, the CSS
Styling the objects with CSS
Styling the ground objects
Writing the JavaScript effects
Setting the row height
Spreading the objects
Spreading the clouds
Loading the page functions
Smoothening the scroll
Updating elements on the scroller
Collecting the moving elements
Creating functions for the element types
Setting the left positions
Creating the rocket's movement function
Finally, moving the earth
Summary
4. Single Page Applications
What is an SPA?
The SPA's relevance
Getting to work
Getting the old files
Getting the project set up
Object and function conventions
Creating utility functions
Creating a services layer for AJAX
Creating and using the file structure
Working with the home structure
Putting the content in the new file structure for the home
Modifying index.html and CSS
Modifying the JavaScript to use the structure
Finish the home to make it work
Setting up other sections
Breaking out the content into directories
Separating concerns and making objects
Making the routing registry tables
Using routing registry tables to load home content
Loading all sections in the structure
Making #hashes
Using #hash for routing
Performing housekeeping
Creating a callBack function for the API
Using the callBack function
Using the callBack function
Adding links that use hashes
Using APIs
Summary
5. The Death Star Chapter
Where to begin?
Deleting unnecessary features
Adding new routes
Adding the directories
Adding levels to JavaScript
Editing home.html
Dropping in the parallax game
Fixing the broken level
Moving the load functions to levels.js
Fixing the namespacing in Level1.js
Loading elements from JSON
Using the data requests
Parsing the AJAX
Moving the spreadObjects function to a general pattern
What can be done in the shared levels service
Updating elements on the scroll
Modifying the CSS
Adding message objects
Creating a clickable object
Creating a moving object
Editing the home JavaScript
Adding more to make the home interesting
Creating the other pages – credits and leaderboard
Replicating credits for the leaderboard
Creating the second level
Getting SVG objects
Creating the directory structure and routes
Creating the new JSON for each level
Creating the level 2 HTML
Creating the level2 JS
Parsing the AJAX
Updating the elements
Moving the elements
Adding some CSS
Creating the home page version
Adding final touches
Creating explosive final touches
Summary
Index

Web Design Blueprints

Web Design Blueprints

Copyright © 2016 Packt Publishing

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

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

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

First published: April 2016

Production reference: 1270416

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78355-211-5

www.packtpub.com

Credits

Author

Benjamin LaGrone

Reviewer

Kryštof Doležal

Commissioning Editor

Edward Gordon

Acquisition Editor

Reshma Raman

Content Development Editor

Sumeet Sawant

Technical Editor

Mohit Hassija

Copy Editor

Madhusudan Uchil

Project Coordinator

Shweta H Birwatkar

Proofreader

Safis Editing

Indexer

Priya Sane

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

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

About the Reviewer

Kryštof Doležal is a web developer from Prague, the capital of the Czech Republic. He has been interested in creating websites since he got his first computer. Kryštof has been a qualified specialist in computer science applications since 2006. He has worked in a TV studio for the ministry of education and AVG Technologies. Now, he works in web development and IT consulting as a freelancer.

www.PacktPub.com

eBooks, discount offers, and more

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

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

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

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

Why subscribe?

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

Preface

Web design is becoming a fragmented and dispersed topic. There are many trends within the industry that allow professional developers to build websites for clients with a growing set of demands. There is currently no documentation that draws all of this information into one place, provides web designers with a panoramic view of their industry, and gives them the necessary skills to go out and make a given website.

What this book covers

Chapter 1, Responsive Web Design, discusses responsive elements, layouts, media, typography, and navigation. It provides the elements to create a good starter template for a responsive website. It discusses RWD basics, the user agent, the media query, responsive images with CSS, responsive images with SRCSET, responsive video, responsive typography, responsive layouts, and responsive menus with CSS and JavaScript.

Chapter 2, Flat UI, teaches you flat user interfaces: what they are, the changes in them, and using color schemes. This chapter takes you through creating a responsive Flat UI layout you can use.

Chapter 3, Parallax Scrolling, begins with taking elements from the two previous chapters and creating a Parallax Scrolling website using modern web elements and graphics.

Chapter 4, Single Page Applications, takes the flat UI layout and turns it into a real dynamic single-page application using nothing but plain vanilla JavaScript.

Chapter 5, The Death Star Chapter, is a challenging boss-level chapter that takes a cumulative approach to all the subjects in the book by building a flat UI, multi-level parallax scrolling, interactive video game.

What you need for this book

You will need an integrated development environment (IDE), a local host webserver, a browser, and your thinking cap.

Who this book is for

This book is a must-have for web developers who want to stay on top of the latest trends in web app and site development. This book is for web developers already familiar with HTML CSS, and functional JavaScript and wanting to learn the latest trends in web development.

Conventions

In this book, you will find a number of text styles 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: " Add a selector for the navButton class to the media query for viewports larger than 480px."

A block of code is set as follows:

<!doctype html> <html lang='en'> <head> <title>Responsive Web Design</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> </head> </html>

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: " Next, launch the file in your browser. Open the Inspector (right-click, and select Inspect Element) and go to the Network Tab."

Note

Warnings or important notes appear in a box like this.

Tip

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 disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

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

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

Customer support

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

Downloading the example code

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

You can download the code files by following these steps:

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

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

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

Downloading the color images of this book

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

Errata

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

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

Piracy

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

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

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

Questions

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

Chapter 1. Responsive Web Design

Welcome to Web Design Blueprints. This book is meant to introduce you to some really cool new web design patterns that have arisen in web development. In this book, you will learn how to create responsive websites, how to create websites using the principles of flat design, make deep-dive sites using parallax scrolling, and use Ajax in single-page apps. Finally, we'll combine all these together into an awesome choose-your-own-adventure-style game.

Introduction to responsive web design

Let's be honest, you already know what responsive web design means. But for the sake of the age-old tradition of pedagogy, I'll explain. Responsive web design is designing a website to optimize for multiple different viewports. What this means is that in this part of the book, I'll be discussing various techniques for creating a webpage that will look good on mobile devices, tablets, desktops, and laptops, and so on.

I'm not a fortune-teller, but I suspect that mobile devices are not disappearing any time soon. In fact, in my work, I've seen the traffic move from desktop to mobile. In many areas, we see that mobile is the primary tool for people's search for information. If it's not the primary one, it's at least a growing audience. Or else, they are the audience that leaves a site that doesn't have a mobile Web presence. Therefore, the demand for web developers who understand responsive design is paramount to the industry. This skill is a must-have if you want to stay current in the developer workforce.

In this chapter, I will discuss responsive elements, layouts, media, typography, and navigation. You can jump ahead to a section you are particularly interested in or read the whole thing from beginning to end. If you follow along through the entire chapter, you should have a good starter template for a responsive website. We'll learn the following:

Responsive web design basicsThe user agentThe media queryResponsive images with CSSResponsive images with srcsetResponsive videoResponsive typographyResponsive layoutsResponsive menus with CSS and JavaScript

Getting familiar with the basics

Before we start, let's go over some basic stuff. There are some trivial and not-so-trivial things that you will need to do to get your responsive site working.

Using the inspector

The first foundational thing you should learn is using your browser's inspector to emulate different devices. There are a number of tools available in this toolset. Let's look at Chrome; first: click on the Chrome menu in the top-right corner of the browser window:

Next, select More Tools | Developer Tools. Then you can right-click on any element and select Inspect Element:

With this tool, you can inspect elements; use the JavaScript console; look at source code, network requests and responses, the timeline, and resources such as session and local storage; and even connect to a device and debug its Chrome browser.

Likewise, in Firefox, select Tools from the menu bar, and then select Developer Tools. You should see this:

Understanding the viewport meta tag

Now, on to our next task: creating the viewport meta tag. Every function of any responsive site you create will depend on this tag. Without it, your site won't be responsive at all!

The viewport meta tag was initially implemented only in Safari but was quickly adopted by other browsers. This clever little tag instructs your browser to render the webpage scale and size in specific ways.

Learning about the viewport meta tag by example

It may be easier to learn about the meta tag by demonstrating what the viewport will look like without it. Without the tag, your webpage will be rendered at full width in mobile viewports. The result will be the text being so small that you will have to pinch out to expand the text to a readable size.

For the sake of proving the point, let's start with a paragraph of text (you can go generate some ipsum text from http://www.lipsum.com/) styled to have a font size of 12px, using the following code:

<!DOCTYPE html> <html> <head> <title>Viewport META Tag Test</title> <style> p{ font-size:12px; } </style> </head> <body> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus feugiat tempor dui, ac volutpat lacus tempus id. Suspendisse feugiat est felis, vitae ultrices neque accumsan non. Curabitur lacus erat, suscipit eget sagittis eu, tincidunt eget urna. </p> </body> </html>

Viewing your work on the tag

Now, save the file and launch it in a browser with a good mobile emulator, such as Google Chrome, or use iOS Simulator. You will find that it is not very readable. All of the text is very tiny. This is what the world would look like without the viewport meta tag. See it illustrated in this screenshot:

Compare it to normal desktop browser rendering. There's a very big difference in the readability. The pixel density of mobile devices changes the way this is rendered, so you will need to account for this by defining the viewport's properties in the meta tag. Here's the desktop browser rendering:

Fixing the problem by adding the proper meta tag

Now let's see what a wonderful world it would be with the addition of the viewport meta tag. Add a very simple version of the tag to the same code in the header, as I have in the following code sample:

<head> <title>Viewport META Tag Test</title> <meta name="viewport"> </head> <body> …

There are a few options for the viewport meta tag; however, only use them if you know what you are doing. These can end up causing more damage than you might anticipate. If you are not sure what you are doing, just keep it simple, Slick.

Further explanation of the viewport meta tag

Let's look at the viewport options in detail, starting with setting the width. You can set the width to a specific number, but that's not recommended. So set the content attribute equal to the device width, as illustrated in the following sample code:

<meta name="viewport" content="width=device-width">

Next, we look at the scaling. This is when you squeeze your two fingers together and apart on the screen to zoom out and in. You can prevent this behavior in the viewport or limit it by setting the maximum-scale attribute equal to 1. You can also predetermine the scale of the webpage when it's rendered initially, by setting the initial-scale attribute. In most cases, I set both as 1; see it in this sample code:

<meta name="viewport" initial-scale=1 maximum-scale=1>

This meta tag will not affect the rendering in the viewport unless it is viewed on a mobile device or proper emulator or simulator. Now, relaunch the file, and you will see that the page behaves much better. See it in this screenshot:

Understanding and changing the user agent string

Every time your audience's browser makes an HTTP request to your server to obtain a webpage, it identifies itself and reveals some things about itself to the server. This information can be used by your code to help create an optimized rendering of the site. The most important information revealed in the user agent string is the browser product name and version (such as Chrome/32.1), the layout engine and version (Gecko/1.1), and usually, the device system product name and version.

Using the user agent string for testing

When creating your responsive website, you will most likely be working directly on your computer, not on a mobile device, and either hosting locally or deploying to a server for production. No matter whether it's local or hosted, even if you're the Nikola Tesla (https://en.wikipedia.org/wiki/Nikola_Tesla) of CSS, you can't guess everything, so you will eventually want to do some visual testing on your site.

Manipulating the user agent string is a good way of simulating what your responsive website will look like in production. There are plenty of tools available to switch the user agent. The Chrome debugger includes a device mode you can toggle in order to simulate the mobile device. In addition to changing the viewport size to match the selected device, this wonderful little tool will switch the user agent string for you, re-rendering your website on the fly (usually, however, you may need to refresh).

How to change the user agent string in Chrome

You can access the toggle device mode from Chrome's developer tools. There are a few ways to get here. First, from the system menu, select View, then Developer, and then Developer Tools. Or you can right-click on an element in the viewport to launch the contextual menu and can then select Inspect Element. Finally, you can use keyboard shortcuts: on a Mac, use Cmd + Opt + I, and on Windows, use F12 or Ctrl + Shift + I.

Once you have the developer tools open, you'll see in the top-left corner of the developer tools section of the viewport an icon of a magnifying glass and, next to it, an icon of a mobile phone. When you click on it, it will toggle the device mode or change the user agent. See this in the following screenshot:

Once you activate this new interface, you will see some new options. First, you may be prompted to refresh the page. Otherwise, on the top, you will see a Device select option, where you can toggle through a list of common devices. Next to it is a Network select option element. With this tool, you can throttle the download speed in order to emulate different network types and speeds to see how slower downloads will affect the rendering of your responsive webpage.

What next?

Other cool features of the inspector are the rulers on the sides that let you get precise reads on the rendering and the touch emulation so that you can see how the user will truly interact with the user interface. Once it is launched, you can keep it running and toggle between different user agents and see how your page is rendered. There are even some views that emulate notebooks. This tool will prove to be one of the most useful tools in your toolbox. You will likely use it for many of the projects following this section.

Using media queries for responsive design

The media query is the philosopher's stone of responsive design. With its logical expression, you can create a webpage that responds and transforms to fit different viewports. A media query contains a media type and one or more expressions that, if true, can invoke new CSS attributes for that expression.

Some background information

There are possibly hundreds of permutations of these expressions; for a moment, take a look at the W3C website for the possible attributes. All of these are available for you to browse through over at http://www.w3.org/TR/css3-mediaqueries/. Here's that list for easy reference:

width: This describes the width of the targeted viewport of the device. It can accept min/max prefixes.height: This describes the height of the targeted viewport of the device. This can accept min/max prefixes.device-width: This describes the width of the rendering surface of the device. It can accept min/max prefixes.device-height: This describes the height of the rendering surface of the device. It can accept min/max prefixes.orientation: This describes the height being larger or smaller than the width. When larger, the value is portrait; when smaller, the value is landscape.aspect-ratio: This is defined as the ratio of the value of width to the value of height. It can accept min/max prefixes.device-aspect-ratio: This is defined as the ratio of the value of device-width to the value of device-height. It can accept min/max prefixes.color: This describes the number of bits per color component on the output device. It can accept min/max prefixes.color-index: This describes the number of entries in the color lookup table. It can accept min/max prefixes.monochrome: This describes the number of bits per pixel in a monochrome frame buffer. It can accept min/max prefixes.resolution: This describes the resolution of the output device. It can accept min/max prefixes.scan: This describes the scanning process of TV output devices.grid: This can be used to query whether the output device is a grid or bitmap.

A small example

A media query can be executed as a condition in a link reference to a stylesheet or within a stylesheet itself. First, let's look at an example of the stylesheet link:

<!-- CSS media query on a link element --> <link rel="stylesheet" media="screen and (max-width:720px)" href="example.css" />

In the example, the stylesheet will be applied to viewports on devices with widths of 400px or lower. The CSS stylesheet link element lives in the <head> tag, before the <body> tag.

The media attribute is the actual query. Here, you can set the conditions that, if true, will load the linked stylesheet. You can add more logic to this media query conditional expression in the media attribute by including and, not, or only to the query expression. You can also specify the media type; however, there are not too many universally useful options here beyond screen and print.

Media queries are most useful when included in the CSS. Here is the place you can make them really work for you and make a fully responsive website.

A better example

Enough explaining; let's jump into some learning by doing. Open up your favorite IDE and create a new HTML file. It should look something like the following code sample. Remember to include your viewport meta tag!

<!doctype html> <html lang='en'> <head> <title>Responsive Web Design</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> </head> <body> … </body> </html>

That was easy, I hope. We need to add some content and markup to that skeletal HTML. Next, within the body, insert a paragraph element with some ipsum text to fill it up, as I have in the following code sample:

<body> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse eget finibus dolor. Cum sociis natoque penatibuset magnis dis parturient montes </p> </body>

Adding style

You've created a simple webpage; next, let's create a stylesheet and try some media queries. Back in the header of the HTML page, add a CSS stylesheet link. This time, include screen and max-width as a feature of the inline media query. See this in the following code sample:

<head> <link rel="stylesheet" media="screen and (max-width: 720px)" href="style.css" /> </head>

In the same directory, create a new file, style.css. Open it in your text editor or IDE and add some style for the <p> element. Give it a font-size value of 12px. This is illustrated in the following code:

p { font-size: 12px; }

Next, we will add a media query to the CSS. The media query will begin with @media and then the operator in parentheses. A bracket {...} will follow, containing the style attributes you want applied for that media query. Let's go through the media queries listed previously. I'll show this in the following code sample:

@media (width:360px) { p { font-size:20px; } }

This media query will apply only when the viewport width is 360px. The result is that the font of the paragraph will render at 20px. That's great, but honestly, it is not very useful, because it will apply only when this condition is true. If the viewport is 361px or 359px, then it is false. This is too laborious to test. Instead, recall that this feature can accept min/max prefixes. So, you can probably guess that I'm going to tell you to prefix the width feature with min or max and show it in a code sample, like this:

@media (max-width:360px) { p { font-size:20px; } }

Viewing your example

Demonstrating this feature will be a snap. Launch the HTML file in your browser and compare the desktop version to what you see when you toggle the display mode in the inspector to a viewport size that is less than 360px. You should be seeing a larger font size when the page is viewed on a mobile device. Try out some of the other media queries mentioned in the previous list to see how they apply; at least try the ones you can test.

Adding complexity to your stylesheet

Next, let's work on some combinations of features to demonstrate how they work together. We will combine two media query features using the conjunction and. Our purpose will be to have a specific style attribute apply only to viewports between two size values. To make a combined media query that applies style attributes only to tablets, we might want the style to apply to all viewports between 360px and 600px. So, let's create a media query for viewport sizes greater than 360px and less than 600px, as I have in the following code:

@media (min-width:360px) and (max-width:600px) { p { font-size:16px; } }

Refresh your browser and you will see that there are now three distinct font sizes rendered in the viewport. Look at this set of screenshots for an example:

Adding more media queries

Let's add just one more media query to get a more complete picture. This next media query should apply to tablets only, so create a new media query for viewports greater than 600px. Take a look at the following code example:

@media (min-width:600px) { p { font-size:14px; } }

See how the sample media queries work: