A Smarter Way to Learn HTML & CSS Learn It Faster. Remember It Longer by Mark Myers
Short Description
A Smarter Way to Learn HTML & CSS Learn It Faster. Remember It Longer by Mark Myers...
Description
Also by Mark Myers
A Smarter Way To Learn HTML & CSS Learn it faster. Remember it longer.
Mark Myers
Copyright © 2015 Mark Myers All rights reserved, including the right to reproduce this book, or any portions of it, in any form. 1.0 http://www.ASmarterWayToLearn.com
Chapters Learn it faster. Remember it longer. How to use this book 1 HTML & CSS 2 Creating paragraphs 3 Creating headings 4 Specifying fonts 5 Linking your CSS to your HTML 6 Specifying a font-size 7 CSS classes 8 Classes not tied to an element 9 Font-weight 10 Font-style 11 Styling bits and pieces 12 Colors 13 Spacing 14 Aligning text 15 First-line indent and blockquote 16 Margins 17 Borders 18 Padding 19 Inheritance 20 Grouping 21 ID 22 Div 23 Images
24 Block vs. inline 25 Adding more info to the image tag 26 Positioning an image 27 Centering an image 28 Floating images 29 Links 30 Link addresses 31 Linking to a location on a page 32 Opening a new window 33 Styling links 34 Clickable images 35 Image maps part 1 36 Image maps part 2 37 Bullet lists and numbered lists 38 Styling lists 39 Styling a list’s markers 40 More CSS selectors 41 Tables: basic structure 42 Tables: headings 43 Tables: spanning columns and rows 44 Tables: borders 45 Tables: spacing part 1 46 Tables: spacing part 2 47 Tables: aligning text 48 Tables: background-color 49 Forms: the form tag 50 Forms: text input
51 Forms: textarea 52 Forms: submit 53 Forms: radio buttons 54 Forms: checkboxes 55 Forms: select box 56 Forms: label 57 Grouping related elements 58 Forms: styling 59 Comments 60 Layout: nested boxes 61 Layout: divs 62 Layout: div widths and centering 63 Layout: side-by-side divs 64 Layout: a modern header part 1 65 Layout: a modern header part 2 66 Layout: a modern header part 3 67 Layout: a modern header part 4 68 Layout: a modern header part 5 69 A vertical navigation bar part 1 70 A vertical navigation bar part 2 71 A vertical navigation bar part 3 72 A vertical navigation bar part 4 73 A vertical navigation bar part 5 74 A horizontal navigation bar part 1 75 A horizontal navigation bar part 2 76 Background images part 1 77 Background images part 2
78 Iframes 79 Embedding YouTube videos 80 Further customizing YouTube videos 81 Embedding Vimeo videos 82 Audio 83 Ems vs. percentages vs. pixels 84 Relative and static positioning 85 Z-index 86 Media queries 87 Min- and max-width, min- and max-height 88 The stuff at the top 89 The meta description 90 Build a site Acknowledgements
Learn it faster. Remember it longer. If you embrace this method of learning, you’ll get the hang of HTML and CSS in less time than you might expect. And the knowledge will stick. You’ll catch onto concepts quickly. You’ll be less bored, and might even be excited. You’ll certainly be motivated. You’ll feel confident instead of frustrated. You’ll remember the lessons long after you close the book. Is all this too much for a book to promise? Yes, it is. Yet I can make these promises and keep them, because this isn’t just a book. It’s a book plus 1,800 interactive online exercises. I’ve done my best to write each chapter so it’s easy for anyone to understand, but it’s the exercises that are going to turn you into a real HTML coder. Cognitive research shows that reading alone doesn’t buy you much long-term retention. Even if you read a book a second or even a third time, things won’t improve much, according to research. And forget highlighting or underlining. Marking up a book gives us the illusion that we’re engaging with the material, but studies show that it’s an exercise in self-deception. It doesn’t matter how much yellow you paint on the pages, or how many times you review the highlighted material. By the time you get to Chapter 50, you’ll have forgotten most of what you highlighted in Chapter 1. This all changes if you read less and do more—if you read a short passage and then immediately put it into practice. Washington University researchers say that being asked to retrieve information increases long-term retention by four hundred percent. That may seem implausible, but by the time you finish this book, I think you’ll believe it. Practice also makes learning more interesting. Trying to absorb long passages of technical material puts you to sleep and kills your motivation. Ten minutes of reading followed by twenty minutes of challenging practice keeps you awake and spurs you on. And it keeps you honest. If you only read, it’s easy to kid yourself that you’re learning more than you are. But when you’re challenged to produce the goods, there’s a moment of truth. You know that you know—or that you don’t. When you find out that you’re a little shaky on this point or that, you can review the material, then re-do the exercise. That’s all it takes to master this book from beginning to end. I’ve talked with many readers who say they thought they had a problem understanding technical concepts. But what looked like a comprehension problem was
really a retention problem. If you get to Chapter 50 and everything you studied in Chapter 1 has faded from memory, how can you understand Chapter 50, which depends on your knowing Chapter 1 cold? The read-then-practice approach embeds the concepts of each chapter in your long-term memory, so you’re prepared to tackle material in later chapters that builds on top of those concepts. When you’re able to remember what you read, you’ll find that you learn HTML and CSS quite readily. I hope you enjoy this learning approach. And then I hope you go on to set the Internet on fire with some terrific webpages.
How to use this book Since you may not have learned this way before, a brief user manual might be helpful. Study, practice, then rest. If you’re intent on mastering the fundamentals of HTML and CSS, as opposed to just getting a feel for it, work with this book and the online exercises in a 15-to-30-minute session, then take a break. Study a chapter for 5 to 10 minutes. Immediately go to the online links given at the end of each chapter and code for 10 to 20 minutes, practicing the lesson until you’ve coded everything correctly. Then take a walk. Don’t wear yourself out. You learn best when you’re fresh. If you try to cover too much in one day, your learning will go downhill. Most people find they can comfortably cover one to three chapters a day. Your experience may vary. If you find some of the repetition tiresome, skip exercises. I wrote the exercises for people like me, who need a lot of repetition. If you’re a fast learner or a learner with some HTML experience, there’s no reason to burden yourself. Click the Skip Exercise and Get Credit button to jump ahead. Skip whole sets of exercises if you don’t need them. Practice as much as you need to, but no more. If you struggle with some exercises, you know you’re really learning. An interesting feature of your brain is that the harder it is for you to retrieve a piece of information, the better you remember it next time. So it’s actually good news if you have to struggle to recall something from the book. Don’t be afraid to repeat a set of exercises. And consider repeating some exercises after letting a few weeks go by. If you do this, you’ll be using spaced repetition, a power-learning technique that provides even more long-term retention. Do the coding exercises on a physical keyboard. A mobile device can be ideal for reading, but it’s no way to code. Very, very few Web developers would attempt to do their work on a phone. The same thing goes for learning to code. Theoretically, most of the interactive exercises could be done on a mobile device. But the idea seems so perverse that I’ve disabled online practice on tablets, readers, and phones. (It also simplified my own coding work.) If you have an authority problem, try to get over it. When you start doing the exercises, you’ll find that I can be a pain about insisting that you get every little detail right. For example, if you omit a semicolon, the program monitoring your work will tell you the code isn’t correct, even though it might run. Learning to write code with fastidious precision helps you learn to pay close attention to details, a fundamental requirement for coding in any language. Subscribe, temporarily, to my formatting biases. Current code formatting is like seventeenth-century spelling. Everyone does it his own way. There are no universally accepted standards. But the algorithms that check your work when you do the
interactive exercises need standards. They can’t grant you the latitude that a human teacher could, because, let’s face it, algorithms aren’t that bright. So I’ve had to settle on certain conventions. All of the conventions I teach are embraced by a large segment of the coding community, so you’ll be in good company. But that doesn’t mean you’ll be married to my formatting biases forever. When you begin coding projects, you’ll soon develop your own opinions or join an organization that has a stylebook. Until then, I’ll ask you to make your code look like my code.
1 HTML & CSS An HTML (Hypertext Markup Language) document is a text file that tells the browser (Chrome, Firefox, Internet Explorer, Safari, and others) how to assemble a webpage. It says to the browser, “Put this heading here. Put that paragraph there. Insert this picture here. Put that table there.” Though it can create webpages with formatting that is sometimes elaborate and even beautiful, an HTML document itself is pure text, without any formatting whatsoever. This means you can’t use a word processing program like Microsoft Word to write HTML, because Word and other word processors add formatting. Instead, you’ll choose from any number of editing programs that produce pure text. The simplest of these is Notepad on a PC and TextEdit, in Plain Text mode, on a Mac. You can also use fancier editing programs. And there are web development tools like Dreamweaver. They all create the pure text required for HTML. My favorite code editor is the open source Brackets, free at http://brackets.io/. When I ask you to do something in Brackets, Notepad, or TextEdit, feel free to substitute any of the alternative editors. Each HTML document creates a single webpage in the browser. If a site has a hundred pages, it has a hundred HTML documents. An HTML document’s name ends with the .html extension, as in about.html or products.html. When you’re looking at a webpage, you can see the name of the page’s HTML document in the browser’s address bar. http://www.ASmarterWayToLearn.com/htmlcss/23.html When the line of characters shown above is entered in the browser’s address bar, the browser loads the HTML document 23.html, and that page is assembled in the browser and displayed on the user’s screen. If a user clicks a link on the page for, say help.html, then the file help.html loads, and that page is displayed. There’s one HTML name you usually won’t see in the browser’s address bar, index.html. That’s the name of the page that loads by default when no HTML document is specified. It’s the site’s home page. So if you enter this in the browser’s address bar… http://www.asmarterwaytolearn.com …the document that loads (with some exceptions) is index.html. All the HTML documents for a site are stored on the web hosts’s server, or, in the case of a big, important site, often on the site owner’s own server. When the browser is
pointed to a page on the site, the browser fetches the appropriate HTML file from the server and displays that page. A browser will also display an HTML document stored on your computer’s hard drive. That will prompt your browser to display the page on your screen. Whereas an HTML document specifies the contents of a webpage—the headings, paragraphs, images, tables, etc.—A CSS (cascading stylesheets) file specifies the styling of that page—fonts, colors, column widths, and the like. Like an HTML document, a CSS file is plain text. You can create it with the same editor you use to create an HTML document. A CSS file has the extension .css. When an HTML document loads, it calls the CSS file that styles its contents. Rather than creating a separate CSS file, it’s possible to include all of the styling specifications in an HTML document. But the preferred way to style webpages is to put all the styling information in a separate CSS file, so that’s what I’m going to teach you. These are the rules I’m going to ask you to follow for naming both HTML and CSS files: Use only lower-case characters. Avoid spaces. Stick to 0-9, a-z, and _. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/1.html
2 Creating paragraphs Let’s get your feet wet. 1. On your hard drive create a folder called my-smarter-site. (If you’re unclear how to create a folder in your particular operating system, Google it. There’s plenty of good Windows and Mac instruction for this online.) 2. Under the my-smarter-site folder create a subfolder called css. (Again, if this isn’t something you know how to do, Google it.) 3. Online, go to http://asmarterwaytolearn.com/htmlcss/practice-2-0.html 4. Copy all the text on the page. 5. Open your plain-text editor (see the last chapter) and create a new document. 6. Paste the copied text into it. 7. Save the document in your my-smarter-site folder as practice.html 8. On the empty line between and type your name. 9. Save the file. 10. Go to Windows Explorer (PC) or Finder (Mac) and double-click the file. And voila! There’s your name, displayed in the browser. You’ve just created and displayed your first webpage. If it doesn’t work, take a look at the sample code at: http://asmarterwaytolearn.com/htmlcss/practice-2-1.html Now, on a new line, add a few more words to your code, so it looks like this. Practice Mark Myers That’s my name. Save the file and display the page, following steps 8 and 9 above. Sample code, if you need it, is at: http://asmarterwaytolearn.com/htmlcss/practice-2-2.html.
But wait! You wrote the text on two lines… Mark Myers That’s my name. But the browser displayed it all on one line. Mark MyersThat’s my name. The problem is that the browser doesn’t recognize a carriage return. When you hit a carriage return in a word processor or your text editor, the application breaks the text you write next into a new paragraph, but when you enter a carriage return in an HTML document, the browser ignores it. If you want to display your two sentences in two separate paragraphs, you have to explicitly tell the browser to do it. You do this with paragraph tags. Practice Mark Myers That’s my name. Revise your practice.html text document to include the tags shown above. Save the file. Display the page in your browser. If you coded correctly, the page will now display the text in two separate paragraphs. Sample code is at: http://asmarterwaytolearn.com/htmlcss/practice-2-3.html. Tags are the commonest feature of an HTML document. You use them for all kinds of things. Look at the 9 lines of HTML above. There are tags on every line. Usually—but not always—HTML tags come in pairs, an opening tag paired with a closing tag. The opening tag consists of some characters enclosed by and >. For example, . The closing tag is the same as the opening tag, except a / follows the opening . But unlike all the other tags you see in the code above, it isn’t paired with a closing tag. It stands alone. The link tag consists of three “equations:” Each equation says that something equals something else. The second something is in quotation marks. 1st “equation”: link rel=“stylesheet” tells the browser that the link relationship is with a stylesheet. 2nd “equation”: This is a useless, vestigial part of the tag, like your appendix. We’ve already told the browser the link is to a stylesheet. All stylesheets end with the extension “css,” and they’re all text documents, so this just repeats what the browser should already know. But we still have to include it (but maybe not for long). 3rd “equation”: href stands for hypertext reference. This part of the tag tells the browser where to find the CSS file to link to. We’ve put it in the css subfolder of the folder where this HTML document resides, the my-smarter-site folder. The file name is “styles.css.” Something to notice about formatting here: There are no spaces in the tag, except
those separating the three “equations.” Enter the link tag in your practice.html document. Save it, and have your browser display the webpage it creates. Expect the paragraphs to be in a serif font and the heading in a sans-serif font, as you specified in the CSS file. Find sample HTML code at: http://asmarterwaytolearn.com/htmlcss/practice-5-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/5.html
6 Specifying a font size Let’s change the font-size of your paragraph text and your h1 heading. Open your styles.css file and add the two lines highlighted below. p { font-family: Georgia, “Times New Roman”, Times, serif; font-size: 1.2em; } h1 { font-family: “Trebuchet MS”, Helvetica, sans-serif; font-size: 2em; } When you specify 1.2em as the paragraph font size, you’re saying (without getting too technical) that you want paragraph text to be 1.2 times the default text size—the size that the browser would display if you didn’t specify a size. If you specified 1em, you’d get the default size. .75em would be three-quarters of default size. 1.5em would be 150% of default size. 3.5em would be three-and-a-half times default size. This may come as a surprise: When you specify 2em as the h1 size, you’re not saying you want the h1 heading to be 200% of the default h1 size, but 200% of the default text size. A 2em heading is the same size as 2em paragraph text. The heading, though, will be bold by default and the paragraph won’t be. Things to notice: font-size: 1.2em; is indented 2 spaces. There is no space between 1.2 and em. The line ends with a semicolon.
Coding Alternatives to be Aware Of Instead of specifying font-size in ems, you can specify it in percentages, pixels, or points. In this program we’ll stick to ems for font-size. Save the CSS file. Display your HTML file. Find sample CSS code at: http://asmarterwaytolearn.com/htmlcss/practice-6-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/6.html
7 CSS classes You’ve specified a font family and a font size for paragraphs and h1 headings. You can also create classes of paragraphs and headings with formatting that varies from general styling for paragraphs and headings. In fact, you can create classes of just about any element on the page for custom formatting. Open your styles.css file and add this style… p.important { font-size: 1.5em; } Save your CSS file. Now you’ve created special styling for a class of paragraphs. This special style named “important” will override the general style that you created earlier. When you say you want text in paragraphs of the class “important” to have a fontsize of 1.5em, you’re saying you want the text to be one-and-a-half times normal size. But what is normal size? It depends on whether you’ve created a general style in your CSS file that applies to the whole page (See Chapter 19). If you haven’t created a general paragraph style, normal size is the browser default size—1em. So then a 1.5em font-size for the paragraph class “important” would be one-and-a-half times the browser default size. The rules for naming classes would fill a book. To keep things simple, I’m going to ask you to use lowercase alphabet letters, hyphens, underlines, and numbers. But don’t start a name with a number. Here’s an example of a class for h3 headings. h3.bigger { font-size: 2.5em; } This class will be 250% of the size of normal text. Again, “normal” means 250% of the size of the browser default text size if you haven’t specified a style for the whole page. If you have styled h3 headings, the “bigger” class of headings will be 250% of that size. Save your CSS file. Open your HTML file and add this line… Warning: We have no slow lorises here. Now the text “Warning: We have no slow lorises here.” will be one-and-a-half times “normal” text size. Things to notice: The class reference is part of the opening p tag, all enclosed in brackets. The class name is enclosed in quotation marks. The closing paragraph tag doesn’t change. It’s still . Note: The same class can be assigned to any number of elements. And you can
assign more than one class to an element. You just separate the class names by a space. Here’s an example. Hey now! Let’s say you’ve created a class named “special” that specifies a font size, a second class called “conspicuous” that displays it in red, and a third class called “enhanced” that specifies a font-weight of bold. In the example above, all three classes will apply to the heading. It will be extra-large, red, and bold. Save your files. Display the page. Sample CSS code: http://asmarterwaytolearn.com/htmlcss/practice-7-1.html. Sample HTML code: http://asmarterwaytolearn.com/htmlcss/practice-7-2.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/7.html
8 Classes not tied to an element If you intend to define a particular class for only one type of element—for example, only paragraph text or only h3 headings—write the element name before the dot and class name, as in… p.special { …or… h3.special { If you want a class to be useable for more than one type of element—for example, both paragraph text and headings—omit the element name. Just write, for example… .special { Open your CSS file and add the style below. .typewriter { font-family: “Courier New”, Courier, monospace; } You’ve created a new style named “typewriter” that will style text in a typewriter font. It could be paragraph text. It could be heading text. It could be other kinds of text elements that I’ll introduce you to later. Notice that there’s no element name, like p or h3, involved here. It’s just a dot with the class name following it. Save the file. Open your HTML file and add the code below. This heading is in typewriter text. This paragraph is also in typewriter text. You’ve assigned the class “code” to a heading and a paragraph. Since your CSS file doesn’t tie the class to any particular element, you can use it for any text element. Save the HTML file and display it. Sample CSS code is at: http://asmarterwaytolearn.com/htmlcss/practice-8-1.html. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-8-2.html.
Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/8.html
9 Font-weight In Chapter 7 you created a paragraph class called “important,” and specified a font size one-and-a-half times “normal.” Now let’s make paragraphs classed as “important” even more important. We’ll bold them. Open your CSS file and add the line highlighted below. p.important { font-size: 1.5em; font-weight: 900; By specifying a font-weight of 900, you’re telling the browser to make all the paragraphs of the class important as bold as possible. The scale for font-weight ranges from 100 through 900—100, 200, 300 and so on. 100 is the lightest weight. 400 is normal. 900 is as heavy as it gets. Now, when the browser encounters a paragraph of the important class, it will display it larger and in boldface. A note about font-weight: As an alternative to the numerical scale, you can use one of four font-weight words: lighter, normal, bold, and bolder. Save your CSS file. Display your HTML file. “Warning: We have no slow lorises here.” should now be in bold. Find sample CSS code at: http://asmarterwaytolearn.com/htmlcss/practice-9-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/9.html
10 Font style You can specify italics for any text. Here’s a class that applies italics to a paragraph. p.standout { font-style: italic; } Here’s a class that applies italics to h4 headings of the class “special”. h4.special { font-style: italic; } Here’s a class that applies italics to any text, whether it’s a paragraph, heading, or some other text element. .emphasized { font-style: italic; } Remember, class names can be anything you like, within the bounds of the naming rules I covered in Chapter 7. Instead of defining CSS classes to italicize text, you can use the tag in your HTML. In the following paragraph, the words “David Copperfield” are italicized.
Leading style manuals say book titles, like David Copperfie An alternative to the tag is the tag. You must be dressed and ready to go. By default, the tag has the same visual effect as the tag. They both italicize text. The main difference is that when a screen reader sees the tag, it puts extra vocal emphasis on the text enclosed in the tag. It doesn’t do that with text. Instead of creating a class for bold text in CSS, you can use the tag in HTML. In the following paragraph the text “Please note:” is bolded. Please note: The flight schedule is subject to change without notice. An alternative to the tag is the tag. By default, the tag has the same visual effect as the tag. They both bold text in most browsers. The main
difference is that when a screen reader sees the tag, the reader may say the text in a lower tone. It doesn’t do that with text. In your CSS file, add a class not tied to an element that italicizes text. In your HTML file code a heading of that class. Then write a one-sentence paragraph. In the paragraph, use the two HTML tags that italicize text and the two HTML tags that bold text. Save the files and display your HTML file. Sample CSS code is at: http://asmarterwaytolearn.com/htmlcss/practice-10-1.html. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-10-2.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/10.html
11 Styling bits and pieces So far you’ve been using CSS to style whole blocks of text—paragraphs and headings. But you can also style bits and pieces of those blocks using the tag. Let’s go back to the emphasized class from the last chapter. .emphasized { font-style: italic; } Since the class, as you defined it, isn’t tied to any particular text element—it isn’t p.emphasized or h5.emphasized but just .emphasized—it can be applied to any text you choose, including part of a paragraph or heading. In the following paragraph the words “so much” are italicized.
I love you so much I have to u In your HTML file italicize a portion of the paragraph you created in the last chapter, using a span class of “emphasized.” Save your HTML file and display it. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-11-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/11.html
12 Colors Let’s say you want to display certain text in red. We’ll call the class standout. .standout { color: #cc0000; } You could, of course, tie the class to a text element. It could be p.standout or h2.standout, for instance. But we’ll make it an all-purpose class so we can use it for any type of text element. Here it is, applied to a single hyphenated word. This is going to be a redletter day! Here it is, applied to a whole paragraph.
Please read this chapter carefully. There img src stands for “image source.” It tells the browser where to find the image. An equal sign comes next. Then there’s the path and file name, all in quotes. There is no closing tag. In the normal flow of HTML code, an image will be placed on the page in the same location as it appears in the code. For example, in the following code… Our founder Our founder is no longer with us, alas. …the photo appears under the heading and before the paragraph. You can, although often not legally, display an image from another website. In that case, you have to include the whole URL. The following displays an image stored in the subfolder “pics” of my website. Unless you tell it otherwise in your CSS file, the browser will place an image all the way over on the left. Later, you’ll learn how to place it where you want it—for example, in the center of the page.
Add an image to your HTML file: http://www.asmarterwaytolearn.com/loris.jpg. Save the file and display it. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-23-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/23.html
24 Block vs. inline Most major HTML elements—headings, paragraphs, lists, tables, and divs—are block elements. When an element is a block element, it means the browser doesn’t put any other element beside it. If you write a heading, then a paragraph, then a list, the heading will begin on a new line. The paragraph will begin on a new line. The list will begin on a new line. Block elements can be placed side-by-side, but only if you specify special styling. Divs are block elements, but we place them side-by-side all the time using something called float, for example when we place a sidebar next to a content section. You’ll learn more about this later. All block elements inside a div own their own horizontal space only inside that div. If your CSS specifies that two divs are to be placed side-by-side, then of course elements of one div will sit next to elements of the other div. It’ll be like two columns, with each element having its own horizontal space, but only within its column. In addition to starting each block element on a new line, the browser will add extra space between them. Later you’ll learn to adjust this space using CSS. Inline elements don’t start on a new line. For example, a link is an inline element. If you write… To find the color that complements your complexion, try our picker.html”>Color Picker. …the a href element doesn’t start on a new line. That’s good, because you want it to be part of the sentence flow, not set off. You may find it surprising that images are inline rather than block elements. If you write… …the three images will be arrayed across the div, if there’s room for them all. You can convert images into block elements using CSS. img.owns-its-own-line { display: block; } Now any image assigned to the class “owns-its-own-line” won’t share horizontal space with other images.
In your CSS file code a class of images that displays as a block. In your HTML file assign that class to the loris image that you’ve already coded. Then duplicate that image tag. Now you have two images of the loris. Save the files and display the page. Sample CSS code is at: http://asmarterwaytolearn.com/htmlcss/practice-24-1.html. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-24-2.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/24.html
25 Adding more info to the image tag In the last chapter you learned to write the minimal amount of code for placing an image on the page. This tag gives the browser the name of the image file and the path where it’s stored. That will get the job done. In practice, though, you’ll want to write a more elaborate tag.
tags, which you never deal with except to write the tags, is the mail truck. How many boxes are contained inside the big outer box (the body), and how many levels of nesting wind up inside it, are decisions you make, depending on what you want your page to look like. At a minimum, most professional websites include a collection of boxes that looks something like this.
Of the boxes shown in the diagram, the only big box that you absolutely must have in your code is the outer box created by the required opening and closing tags. You can, if you choose, put all of your headings, paragraphs, images, and links inside that one big, undifferentiated box, and some people do. You’ve seen such pages. The text stretches all the way across the browser window. There’s no layout, really. You exit the site as fast as you can. The diagram above shows the boxes that represent major sections of the page. If I had wanted to show all the smaller boxes that are contained within those boxes, I would have included the boxes containing text. These boxes are created by opening and closing tags, opening and closing heading tags, opening and closing tags, and opening and closing tags. On an HTML page, everything is inside something else. Whenever you write an HTML tag, you create a box. The opening and closing tags in the following example create a box containing the text “Hey now!” Hey now! In the following example the opening and closing tags create a box containing the text “Stack Overflow.” a href=“http://www.stackoverflow.com”>Stack Overflow For any box of any size, its contents are affected by any styles you specify for that box. So if you write… p { color: purple; } …all the text enclosed by an opening tag or a closing tag will be, God help you, purple. …unless you make an exception. For example, you can write… .sane-color { color: black; } Then, although the general style for paragraphs is still purple, any text enclosed by a tag that begins The Metropolitan Opera, commonly referred to as the “Met”, is profit Metropolitan Opera Association, with Peter Gelb as etc. Things to notice: There’s an opening tag and a closing tag. src=”[URL]” specifies the location of the HTML file that’s to be imbedded, the same way src=”[URL]” specifies the location of an image file. I’ve shortened the URL so you can focus on the syntax. You specify width and height in pixels. Scrollbars allow the user to explore the whole embedded page. You can wrap text around an iframe. This is the CSS. iframe { float: left; margin: 0 2em 0 0; } In your HTML, create an iframe that embeds an online webpage of your choice. Save the file. Display the page. Adjust the dimensions of the iframe until you’re happy with the result. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-78-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/78.html
79 Embedding YouTube videos There are several ways you can add video to your website. The easiest is to embed a YouTube or Vimeo video. Plus, when you let YouTube or Vimeo host the video free instead of storing it on your webhost’s server, you avoid possible extra charges your webhost might hit you with for using extra bandwidth (video is a bandwidth hog). For complete control, you can host videos yourself. The vast majority of site owners don’t do it, though, because it’s a headache—and not just a regular headache but a migraine. Because makers of devices, operating systems, and browsers can’t agree on one video standard, you have to create a variety of different video files if you want your video to be seen by everybody. You’re a shoe manufacturer who has to make sixteen different sizes. Since it’s so much easier to let YouTube or Vimeo handle the compatibility issues, that’s what I’m going to focus on. In the last chapter you learned how to place an exterior page inside an HTML page by coding an iframe. That’s the method you use to embed a YouTube or Vimeo video. Let’s start with YouTube. You can find out how to post a YouTube video at YouTube or elsewhere online. I’m going to assume you’ve produced your video and posted it to YouTube. Here’s how to put it on your webpage. 1. Find your video on YouTube. Locate “Share” under the video window and click it. 2. Click “Embed.” 3. Click “SHOW MORE.” 4. Scroll down to see some choices you can make. 5. Click the Video size dropdown, and you can choose from four standard video sizes. You can also choose “Custom.” If you choose a custom size, be sure to keep the ratio of width to height at 16 to Otherwise, the picture will distort. To remember the ratio, picture a young person in the U.S. getting her driver’s license (16 years old), and driving the number 9 around. You can also use a ratio of 4 to 3. If you do, you’ll need to change the Aspect Ratio on your video’s Player controls panel. See the next chapter for more on this. 6. Next, look at the other choices you have, below the Video size dropdown. You’ll want to uncheck “Show suggested videos when the video finishes,” unless you
want the user to choose from a gallery of more YouTube videos when your video finishes. “Enable privacy-enhanced mode” means that YouTube won’t store information about visitors to your site unless they play the video. In most cases, you won’t care about this. 7. When you’ve finished making your selections, copy and paste the YouTubegenerated iframe code into your HTML document. 8. If you’d like to add a frame border, change the “0” to a “1”.
9. If you don’t want the user to be able to enlarge the frame to fullscreen size, delete allowfullscreen.
In your HTML file, replace the iframe you coded for the last chapter with an embedded YouTube video. It doesn’t have to be your own video. Use mine if you like: https://www.youtube.com/watch?v=_tky2rAxBIU Save the file. Display the page and play the video. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-79-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/79.html
80 Further customizing YouTube videos When you’re embedding a video on your site, you may not want a YouTube video to look like a YouTube video. You may want it to display without the YouTube branding and controls. When you banish the YouTube branding and controls, a YouTube logo will appear in the lower right corner before playback and when the user mouses over the video, but otherwise, you’ve got a video that looks proprietary. You can choose from a number of options to make the video look and perform the way you want it to. But you have to go to Google, the owner of YouTube, to do it. Begin by copying your video’s YouTube ID from the YouTube URL for your video. It’s the code that follows the equal sign. Alternatively, you can copy the ID from the iframe code that YouTube originally generated for you. Note that the ID ends at the last character before the question mark. Go to: https://developers.google.com/youtube/youtube_player_demo. Paste your video’s ID into the video ID field. Click “Update player with selected options. Google replaces the demo videos with your video when you click “Update player with selected options.” If your ID is correct, the four video thumbnails are replaced by your video. It plays. You can pause it while you choose custom options. Next, click the Show player parameters button at the top of the panel. Another panel with an array of customizing choices displays. Click modestbranding to banish the YouTube logo. When you’ve finished making selections, once again click “Update Player with Selected Options” at the top of the panel. The iframe embed code changes to reflect your selections. Copy and paste it into your HTML document. In your HTML file, change your embedded video so it has modest branding. Save
the file. Display the page. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-80-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/80.html
81 Embedding Vimeo videos If YouTube is the network TV of online video, Vimeo is cable. It’s a little classier, looks a little better, and is preferred by many creative people. It’s free for the basic service. You can remove all Vimeo branding if you’re willing to pay $199 a year. The process of embedding a Vimeo video is similar to YouTube’s. I’m assuming you’ve produced your video and posted it to Vimeo. Here’s how to put it on your webpage. 1. On your Videos page at Vimeo locate the video you want to embed. Click the paperairplane icon at the upper right. 2. A new window opens. If you don’t choose to customize, copy the iframe code and paste it into your HTML document, and you’re done. 3. To customize, click + Show Options. 4. Select the options to change from the dropdown. 5. In the options panel you can specify the dimensions of the video player. Change the width or the height. Vimeo will automatically change the other dimension to preserve the ratio of 16 to 6. By clicking on a color block or specifying a color by hex code you can change the color the video title. The color of the progress bar will change to match. 7. For a clean look, you’ll probably want to uncheck Portrait, Title, Byline, and Show text link underneath this video. 8. To make the video play automatically, check Autoplay this video. To make it loop check Loop this video. Chances are, you don’t want a video description. If you don’t, leave the last item unchecked. 9. Copy the embed code and paste it into your HTML document. For $59.95 a year Vimeo gives you additional customization options and other privileges including faster conversion. For $199 a year, the Vimeo logo goes away; you can, if you wish, insert your own logo. In your HTML file, replace the embedded YouTube video with an embedded Vimeo video. Use mine if you like: https://vimeo.com/97326700 Since you’re running the HTML locally rather than on the Web, you need to insert http: at the beginning of the video URL so your page can connect to the video online. Save the file. Display the page. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-81-1.html.
Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/81.html
82 Audio It’s far easier to host your own audio files than your own video files, because the compatibility issues are tamer. If you use Audacity or another audio editor to save your file in just two formats, mp3 and Ogg Vorbis, your audio will play in any modern browser, using HTML5. This is the code. If a particular browser can’t handle the Ogg Vorbis file, it’ll play the mp3 file. The audio tag shown above includes the optional controls. This tells the browser to make the player visible and allow the user to control it. An alternative is to have the audio autoplay, with or without controls. The following code starts the audio automatically, without a visible player. The following code starts the audio automatically and displays controls. Be careful with autoplay. In most situations, users find it annoying. You can add a paragraph inside the audio tags that displays if the user has an antique browser that doesn’t handle HTML5.
This browser doesn’t support our audio format. In your HTML file, insert a at the bottom, then embed the audio files http://www.asmarterwaytolearn.com/boing.ogg and http://www.asmarterwaytolearn.com/boing.mp3. Save the file. Display the page. Play the audio. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-82-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/82.html
83 Ems vs. percentages vs. pixels Ems, percentages, and pixels are three different units of measurement that you use to style the elements of a webpage. They’re somewhat interchangeable. That is, although I’ve taught you, for example, to express font-size in ems, you can, if you like, express it in pixels or as a percentage. Pixels are easy to work with, because they’re simple and absolute. With pixels, you don’t have to deal with the sometimes confusing relativism of ems and percentages. But the problem with pixels is that they are absolute. A CSS file full of pixel specifications doesn’t adapt to different-size screens, because it isn’t relative. The need for responsive design forces us to limit our use of pixels and stick mostly to ems and percentages. Here are the rules of thumb that many developers follow, and that I usually follow in this book. Ems — Use them for typography, margins, and padding. Percentages — Use them for divs, tables, iframes, and sometimes margins and padding. Pixels — Use them for images, borders, windows, iframes, and fixed, absolute, and relative positioning (see next chapter). In your CSS file, style a new div class. Make it less than the full width of the window. Then style a new paragraph class. Make it less than the full width of the div and center it. In your HTML file, code a div of that class and, within it, a paragraph of that class. Save the files. Display the page. Sample CSS code is at: http://asmarterwaytolearn.com/htmlcss/practice-83-1.html. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-83-2.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/83.html
84 Relative and static positioning As you know, the browser displays the elements of your page in the same order in which you write them in your HTML document. If you write a heading, follow it with a paragraph, follow that with a table, and follow the table with a second paragraph, the browser will display everything in that order: Heading Paragraph 1 Table Paragraph 2 But as you saw in Chapters 64 and 67, you can interfere with this natural order. In those chapters, you learned how to position a header exactly where you want it regardless of its order in the HTML document using absolute and fixed positioning. So, with absolute and fixed positioning, where you place the code in the document doesn’t affect its position on the page. You could add the code to the very end of the body section, put it somewhere in the middle, or start it off at the beginning. Its location on the page is determined by the position you specify in your CSS, not its position in the HTML document. And remember, with these types of positioning, all the other elements behave as if they don’t know the element is there. They don’t make room for it, as they do for normally positioned elements. This creates overlap unless you pull a trick like the one you learned in Chapter 68, creating an invisible copy of the header that’s positioned normally and so acts as a spacer, to keep the other normally-positioned elements from disappearing underneath the fixed-position header. Both absolute and fixed positioning specify spacing in terms of how far they are from the edges of the browser window. A third way to interfere with the browser’s default layout is to specify relative positioning. Relative positioning tells the browser to position an element a certain distance from its normal position. For example, if you wanted to position some paragraphs 50 pixels below their normal position, you could write, for example… p.spaced-out { position: relative; top: 50px; } If you wanted a table pushed up and nudged left, you could write, for example…
table#adjusted { position: relative; bottom: 25%; right: 35%; } In relative positioning the other elements don’t adjust to the relatively positioned element’s altered position. They behave as if the element were in its normal position. So, as with absolute and fixed positioning, it’s possible to have overlap. If necessary, you can solve this with a spacing tactic similar to the one you learned in Chapter 68. In most circumstances, you don’t have to tell the browser to position an element normally, since that’s the default. But just so you know, a normally positioned element has static positioning. div.normal { position: static; } In your CSS file, use relative positioning to move the div that you created for the last chapter to the right. Save the file. Display the page. Sample CSS code is at: http://asmarterwaytolearn.com/htmlcss/practice-84-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/84.html
85 z-index In the last chapter you learned that when you override the normal flow of a webpage by using fixed, absolute, or relative positioning, elements may overlap each other. Occasionally, you may want this to happen. For example, you might want to overlay a heading on top of an image. You want the heading to be on top of the image, not the other way around. How do you tell the browser to put the heading on top? By specifying a z-index for the heading. The higher the z-index, the higher it goes in the stack. An element with a zindex of 10 will sit on top of an element with a z-index of 9. The default z-index of elements is 0. So if you give your heading a z-index of 1, it’ll be placed on top of the image, which, assuming you haven’t assigned it a zindex, has a z-index of 0. h2#header { z-index: 1; } If you give it a z-index of -1, it’ll be one layer below the default. 1. In your CSS file, code a div id. 2. Fix its position at the bottom-left. 3. Give it a z-index of -1. 4. In your HTML file, code the id. Place an image inside it: http://www.asmarterwaytolearn.com/monarch.jpg. 5. Save the files. Display the page. Scroll and see what happens. Sample CSS code is at: http://asmarterwaytolearn.com/htmlcss/practice-85-1.html. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-85-2.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/85.html
86 Media queries These days, you almost have to make your site responsive. That means creating custom styling for screens of different sizes, from the smallest phone to the largest desktop. For example, five medium-size images arrayed across the screen are fine if the screen is 1280 pixels wide. But not if it’s a 480-pixel iPhone screen. On a phone, you’ll want to force them to stack vertically. To create different style rules for different screens, you write media queries. For example, a media query asks, “Is the screen no wider than x pixels and no narrower than y pixels? If so, follow these style rules.” Responsive design can be a maddeningly complicated business and deserves a book of its own, but I want to give you a sense of how it works, so I’ll show you one example. There are various ways to incorporate media queries in your code. I’ll show you how to add them to a stylesheet. There are thirteen different media characteristics you can test for in a media query, including color and whether the user is looking at a mobile device in portrait or landscape orientation. I’ll focus on the most common tests, for a screen of any kind (that is, not a printer) and for minimum device width and maximum device width. Here’s some code. @media only screen and (min-device-width: 320px) and (maxdevice-width: 480px) { img.gallery { display: block; } } The code above specifies block—that is, one on each line—for the “gallery” class of images when displayed on a phone, a device we define as having a minimum width of 320 pixels and a maximum width of 480 pixels. Let’s look at each piece of the code. @media is how all media queries begin. @media only screen and (min-device-width: 320px) and (maxdevice-width: 480px) { img.gallery { display: block; }
} only screen means the style rule applies only to devices with screens. This means it doesn’t apply to printers. @media only screen and (min-device-width: 320px) and (maxdevice-width: 480px) { img.gallery { display: block; } } When you write and in a media query, you’re saying, “The following must also be true in order for the style rule to apply.” So it’s not enough for the device to be a screen. It must be a screen and the minimum device width must be 320 pixels (portrait mode) and the maximum device width must be 480 pixels (landscape mode). @media only screen and (min-device-width: 320px) and (maxdevice-width: 480px) { img.gallery { display: block; } } The device-width specifications must be enclosed in parentheses. @media only screen and (min-device-width: 320px) and (maxdevice-width: 480px) { img.gallery { display: block; } } By writing display: block, you tell the browser not to float the images. @media only screen and (min-device-width: 320px) and (maxdevice-width: 480px) { img.gallery { display: block; } } The following media query tells the browser to float the images when they’re displayed on a desktop or laptop, defined as having a minimum width of 1224 pixels. Note that there’s no maximum width, since we’re testing for just one orientation. @media only screen and (min-device-width: 1224px) { img.gallery { float: left; } }
1. In your CSS file, code a media query that styles a class of paragraph in the fontfamily “Comic Sans MS”, cursive, sans-serif—if the screen is at: least 800 pixels wide. 2. In your HTML file, code a paragraph of that class. 3. Save the files. Display the page. Sample CSS code is at: http://asmarterwaytolearn.com/htmlcss/practice-86-1.html. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-86-2.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/86.html
87 Min- and max-width Min- and max-height Suppose you’ve styled a div to occupy 20% of the width of the screen. This works fine as long as the screen is large, but what happens on a phone with a 320-pixel screen? The div width shrinks to 64 pixels—a narrow stripe down the page with room for one or two words per line. To prevent this, you specify a min-width. div#additional-info { width: 20%; min-width: 200px; } Now the div will run 20% of the width of the screen—but only as long as the width doesn’t go below 200 pixels. When that point is reached, your CSS tells the browser to make the width 200 pixels. Then there’s the opposite problem. You’ve created a div that runs 40% of the width of the screen. A block of text inside this div might measure a user-friendly 12 to 14 words wide. But when the same page is displayed on an oversize screen, it could stretch to 20 words wide. That’s too wide for easy reading. So you specify a max-width. div#main { width: 40%; max-width: 500px; } Now, on a wide screen, the width will shrink to 500 pixels when 40% translates into more than 500 pixels. You can also establish limits on height, using max-height and min-height. p.article { min-height: 150px; max-height: 600px; } A problem occurs when the content of an element exceeds the max-height that you’ve specified for the element. In the example above, you tell the browser to limit the paragraph to a height of 600 pixels. If the text in the paragraph runs, say 750 pixels high, the text overflows, potentially creating a mess. You solve this with overflow: hidden or overflow: scroll. In the following example, you tell the browser to make any overflowing content invisible.
p.article { min-height: 150px; max-height: 600px; overflow: hidden; } In the following example, you tell the browser to display a scroll bar that allows the user to scroll down to any overflow. p.article { min-height: 150px; max-height: 600px; overflow: scroll; } 1. In your CSS file, code a class of paragraph with a max-width of 100 pixels and a max-height of 100 pixels. Make the overflow scroll. 2. In your HTML file, code a paragraph of that class, including at least a dozen words. 3. Save the files. Display the page. Sample CSS code is at: http://asmarterwaytolearn.com/htmlcss/practice-87-1.html. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-87-2.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/87.html
88 The stuff at the top The standard code you find at the top of an HTML document is gobbledygook, but as a conscientious coder, you’re always going to include it, so you may as well know what it means. The first line in the document is the doctype declaration. This tells the browser the document is written in HTML5. This is what you’ll always write when you’re creating a new document, whether the document has any HTML5 features in it or not. Things to notice: 1. The exclamation point. 2. It’s in all-capital letters, a convention not a requirement. 3. There’s no closing tag. Next comes the tag. To keep things simple, I’ve coded it minimally in previous chapters, but the recommended way to write it is like this. That little bit of extra information tells the browser, the search engines, and screen readers that the text content of the page—the headings, paragraphs, and tables—are in English. If your page is in Italian, you’d write lang=“it”; in Hindi, lang=“hi”; etc. As you know, the tag is closed with at the end of the document. The tag, which you’re familiar with, goes on the third line. It is closed with the tag at the end of the head section. At a minimum, the head section contains… This tag tells the browser to use a particular flavor of text encoding that permits the greatest variety of characters, thus accommodating the greatest number of languages. The tag isn’t closed. Next, you’ll write opening and closing title tags. Inside them you’ll write the text that will appear in the browser toolbar, in a bookmark list, and in search engine results. Give each page a unique title that describes its particular contents.
Characteristics of the Slow Loris In your HTML file, code the first two tags at the top of a document. Code the meta charset tag beneath the head tag. Save the file. Display the page to be sure your changes haven’t broken anything. Sample HTML code is at: http://asmarterwaytolearn.com/htmlcss/practice-88-1.html. Find the interactive coding exercises for this chapter at: http://www.ASmarterWayToLearn.com/htmlcss/88.html
89 The meta description If you’re hoping people will find your page through a search engine and then click on the link, you need a meta description. A good meta description doesn’t improve your search ranking, but it does increase clicks, because search engines display the description in the search result. When I googled “Carlypso,” Google displayed this result… www.carlypso.com Sell your car with Carlypso. Get up to 40% more than trade-in with the same convenience. The two sentences following the link are the meta description coded into the Carlypso home page. Can you see why having Google display these sentences would increase the number of clicks? You write the meta description in the head section of your page.
Sell Your Car Hassle-Free Things to notice: It begins with
View more...
Comments