1 GETTING STARTED IN WEB DESIGN OVERVIEW • Website creation roles • Equipment • Software Website Creation Roles Content Design Coding: Frontend Coding: Backend Content Information architecture Organizes content logically for ease of findability Content strategy Ensures that text supports the brand/marketing goals; may include data modeling and updating schedules as well as extending brand voice to social media Design User Experience (UX) Makes sure whole experience with the site and the product is favorable based on user testing Interaction Design (IxD) Focuses on how to use the site, including its User Interface (UI) Visual Design Creates the “look and feel” of the site Coding: Frontend Development Authoring/Markup (HTML) Styling (CSS) JavaScript and DOM Scripting Frameworks Coding: Backend Development Server software (ex: Apache, MS IIS) Web application languages (ex: PHP, Ruby, .NET) Database software (ex: MySQL, Oracle) Other Web Roles Product manager Guides product in a way that meets business goals Project manager Coordinates team, schedule, and processes SEO specialist Ensures site is highly ranked in web searches Multimedia producer Creates sound, video, animation, and interactive media. Typical Equipment Solid up-to-date computer Large monitor (or several) Second computer for testing Mobile devices for testing Scanner and/or camera (for artwork) Software Typically Used Coding tools User Interface/layout tools Web graphic creation tools Variety of browsers File management/transfer tools 2 HOW THE WEB WORKS OVERVIEW • The internet vs. the web • History of the web • What servers do • What browsers do • URLs • How web pages are constructed Internet vs. Web internet International network of connected computers protocol A standardized method for transferring data or documents over a network (for example, FTP, STMP, HTTP) web Information shared over the internet using the Hypertext Transfer Protocol (HTTP), which is one of many ways to share information over the internet A Brief History of the Web • Started at CERN, a particle physics lab in Geneva, Switzerland • 1989: Tim Berners-Lee proposed a system for sharing documents via “hyperlinks” • 1990: Prototypes built, first by Tim B-L, then Robert Cailliau • 1992: Approximately 25 servers worldwide • 1993: Web opened up for commercial use The Web Server server A program that delivers documents and data on request web server Any computer running web server software . The Web Server (cont’d) IP address A unique number assigned to a device connected to the internet (IP = Internet Protocol). Example: 199.27.145.64 Domain Name System (DNS) A system that allows internet users to refer to servers by name rather than number Domain name A name assigned to a web server (easier to use than IP numbers). Example: oreilly.com DNS server A server that matches domain names to their respective IP addresses The Browser • The software that requests data or documents from the web server • Also referred to as the client or user agent • Could be on a desktop machine, smartphone, other connected device, or an assistive device such as a screen reader • The program in the browser that interprets HTML/CSS/JavaScript is called the rendering engine Server-side vs. Client-side Indicates which machine is doing the processing: • Client-side applications run on the user’s machine • Server-side applications use the processing power of the server Web Page Addresses (URLs) URL = Uniform Resource Locator Every page and resource on the web has its own URL Parts of a URL 1. Identifies the protocol as “web” (HTTP) 2. Identifies the site by its domain name 3. Path through directories on the server to the target file What’s Going On with Simple URLs http://example.com/index.html 1. The protocol is implied and will be added by browser 2. Domain name is identified 3. If there is no path or filename, it means the URL is pointing to a default file (usually index.html) Anatomy of a Web Page The page you see in the browser window is nearly always made up of multiple files, including: • An HTML document (gives the content structure) • Style sheets (describes how it should look) • Images and other media (embedded on the page on the fly) • Scripts (add behaviors and functionality) A Web Page and Its Components What Style Sheets Do Browser’s default rendering Simple style sheet applied Web Page Assembly Process 1. Request a page using its URL 2. Browser sends HTTP request to server 3. Server returns the file (or a “404 Not Found” message) 4. Browser looks at the HTML document. If there are external files (like images or style sheets), it contacts the server again for each resource 5. The server returns the additional files, and the browser assembles the final page 3 SOME BIG CONCEPTS YOU NEED TO KNOW OVERVIEW • Multitude of devices • Web standards • Progressive enhancement • Responsive web design • Accessibility • Site performance A Multitude of Devices • Your web pages will be viewed on all manner of devices, large and small, fast and slow, visual and non-visual. • One of the challenges of being a web designer is creating a good experience regardless of the browsing device. Brad Frost’s depiction of the web viewing environment. Web Standards • The World Wide Web Consortium (W3C) writes the specifications for web technologies: w3.org/standards • Sticking with web standards ensures consistency across browsers and forward-compatability. Progressive Enhancement Progressive enhancement is a strategy for coping with unknown browser capabilities. • Start with baseline experience that provides content and basic functionality even on minimal browsers and assistive devices • Layer on styles, scripts, and advanced features for browsers that can handle them • Finish with “nice to have” effects (like animation) that aren’t critical to the brand or functionality Progressive Enhancement (cont’d) HTML strategy Write in a logical order, with elements marked up in a meaningful way Style strategy Use universally supported properties as the baseline and add cuttingedge styles as embellishment Scripting strategy Make sure basic functionality (like content display, linking, and forms) are possible when JavaScript is turned off. Enhance the experience when JavaScript is available Responsive Web Design Responsive web design is a strategy for dealing with unknown screen size: • The heart of the method is using one HTML source for all devices and swapping out the styles based on the size of the browser window (viewport) • It is preferred to building separate sites just for mobile devices (“m.dot” sites) • It may not be the solution for all sites, but making sites that adapt to screen size is now common practice Responsive Web Design (cont’d) Page layout changes based on the width of the screen. Accessibility • Users access web content in many ways: Keyboard, mouse, voice commands, screen readers, Braille output, magnifiers, joysticks, foot pedals, and so on • Four broad categories of disabilities affect how people interact with computers: • Vision impairment • Mobility impairment • Auditory impairment • Cognitive impairment Accessibility (cont’d) • There are measures you can take to improve the accessibility of your web pages. • The Web Accessibility Initiative (WAI) is the group responsible for making web technologies accessible: www.w3.org/WAI. • The WAI-ARIA (Accessible Rich Internet Applications) specification documents accessibility features. Site Performance • It is critical that web pages display as quickly as possible. • Users on mobile devices generally leave a page if it does not display in 3 seconds. • Even milliseconds can affect the bottom line on retail sites. Site Performance Tips • Make image files as small as possible. • Streamline HTML markup. • Keep JavaScript to a minimum. • Add scripts in a way that they don’t block page rendering. • Don’t load unnecessary assets. • Reduce the number of times the browser makes requests of the server. Site Performance Tools • Use a waterfall chart to see what assets are downloading for your page and how many milliseconds they take. • This tool is built into the Chrome browser (Developer > Developer Tools). 4 CREATING A SIMPLE PAGE (HTML OVERVIEW) OVERVIEW • How markup works: Elements and attributes • Minimal HTML document structure • Identifying text elements: Block and inline • Troubleshooting and validating HTML Content Without Markup Without HTML markup to describe content structure, text runs together; line breaks are ignored: Black Goose Bistro The Restaurant The Black Goose Bistro offers casual lunch and dinner fare in a relaxed atmosphere. The menu changes regularly to highlight the freshest local ingredients. Catering You have fun. We'll handle the cooking. Black Goose Catering can handle events from snacks for a meetup to elegant corporate fundraisers. Location and Hours Seekonk, Massachusetts; Monday through Thursday 11am to 9pm; Friday and Saturday, 11am to midnight What Browsers Ignore • Multiple character spaces (white space) • Line breaks (carriage returns) • Tabs • Unrecognized markup Markup Basics Text must be marked up meaningfully and accurately (semantically) with HTML tags: • Browsers need markup to display content correctly. • Markup makes content elements available to scripts and style rules. • Markup aids search engines. Anatomy of an HTML Element tag The element name in angle brackets element The content and its markup (start and end tags) Some Elements Are Empty Some elements have no content and provide a simple directive. They are called empty elements: Attributes Attributes are instructions that clarify or modify an element. They appear in the opening tag after the element name: <element attribute="value">Content</element> <a href="http://oreilly.com">O’Reilly site</a> Attributes (cont’d) There can be more than one attribute in a tag: They are separated by spaces and can go in any order. Attributes (cont’d) • Most attributes take values, which follow an = sign; some are single descriptive words. • A value might be a number, word, string of text, URL, or measurement. • Quotation marks aren’t strictly required but are recommended for consistency. • Single or double quotation marks are okay. • Attribute names and values are defined in the HTML specification. • Some attributes are required. Nesting Elements Putting elements inside other elements is called nesting. Make sure closing tags don’t overlap: <div> <h1>Headline</h1> <p>This is <em>emphasized</em> text.</p> </div> HTML Comments To leave a note in an HTML document, mark it up as a comment: <!-- start global navigation --> <ul> … </ul> <!-- end global navigation and begin the main header for content page --> Text between <!-- and --> won’t display in the browser. Keep in mind that they are still visible in the source. Minimal Document Structure It is recommended that HTML documents have the following minimal structure: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title here</title> </head> <body> <!-- Page content goes here.--> </body> </html> Minimal Document Structure (cont’d) The DOCTYPE declaration lets browsers know that the document is written according to the HTML5 specification: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title here</title> </head> <body> [Page content goes here.] </body> </html> Minimal Document Structure (cont’d) The html element is the root element that contains all the elements in the document: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title here</title> </head> <body> [Page content goes here.] </body> </html> Minimal Document Structure (cont’d) The head element contains elements that pertain to the document and are not rendered as content, such as title, metadata, style sheets, and scripts: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title here</title> </head> <body> [Page content goes here.] </body> </html> Minimal Document Structure (cont’d) meta elements provide document metadata. In this case, it says that the document uses an expanded character set (UTF-8). It could also provide keywords, author information, publishing status, and more: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title here</title> </head> <body> [Page content goes here.] </body> </html> Minimal Document Structure (cont’d) The title element is required. Titles display in the browser tab and bookmark lists, and are used by search engines: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title here</title> </head> <body> [Page content goes here.] </body> </html> Minimal Document Structure (cont’d.) The body element contains the content of the document. The content is everything you want to show up in the browser window: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Title here</title> </head> <body> [Page content goes here.] </body> </html> A Structured Document With the document structure in place, there is a title in the browser tab, but the content is still unstructured. <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Black Goose Bistro</title> </head> <body> Black Goose Bistro The Restaurant The Black Goose Bistro offers casual lunch and dinner fare in a relaxed atmosphere. The menu changes regularly to highlight the freshest local ingredients. … Location and Hours Seekonk, Massachusetts; Monday through Thursday 11am to 9pm; Friday and Saturday, 11am to midnight </body> </html> Marking Up Content • The purpose of HTML is to add meaning and structure to the content. This is called semantic markup. • It is not intended to describe how the content should look (its presentation). • The way elements relate to one another forms an outline-like structure called the DOM (Document Object Model). • The DOM is the foundation on which you apply styles and scripts. Basic Text Elements With headings (<h1>) and paragraphs (<p>) identified, the browser can display the content appropriately: … <body> <h1>Black Goose Bistro</h1> <h2>The Restaurant</h2> <p>The Black Goose Bistro offers casual lunch and dinner fare in a relaxed atmosphere. The menu changes regularly to highlight the freshest local ingredients.</p> <!--more content--> </body> Block and Inline Elements Block elements Major components of the page that display like rectangular blocks stacking up on the page Example: headings, paragraphs, long quotations Inline elements Appear within the text flow of a block element Example: emphasized text, links, abbreviations Block and Inline Elements (cont’d) Block elements (headings, paragraphs) outlined in RED. Inline element (emphasized text) outlined in BLUE. Style Sheets • HTML only describes structure, not presentation • Presentation is controlled by style sheets (CSS) • Browsers have their own style sheets (user agent style sheets) with default styles for HTML elements • You can write your own styles to override the default styles Style Sheets (cont’d) The browser parsed the markup and used its built-in style sheet to format the text elements in the example: Margin around page Headings bold and large Space added above block elements Emphasized text in italic font Troubleshooting HTML Small mistakes and missing characters can cause HTML documents to “break.” Common mishaps: • Missing closing tag (or / in closing tag) • Missing closing bracket in a tag • Missing quotation mark around an attribute value • Not saving your document before viewing changes in the browser Troubleshooting (cont’d) When a slash is omitted, the browser doesn’t know when the element ends: Troubleshooting (cont’d) A missing end bracket makes the browser interpret all the following characters as part of the tag: Validating Your Documents Validate a document to make sure that you have abided by the HTML rules and that there are no errors: • Include the DOCTYPE declaration • Indicate the character encoding • Include required attributes • Don’t use non-standard elements • Don’t mismatch tags • Nest elements correctly (no overlaps) • Check for typos and other minor errors Validating Your Documents • Use a validator tool like the one at html5.validator.nu. • Upload a document or provide a link, and the validator returns an error report. 5 MARKING UP TEXT OVERVIEW • General block elements • Breaks • Lists • Page organizing elements • Inline elements • Generic elements • ARIA introduction • Escaping characters Markup Tips • It is important to mark up content semantically, in a way that accurately describes the content’s meaning or function. • This ensures your content is accessible in the widest range of viewing environments: • Desktop and mobile browsers • Assistive reading devices • Search engine indexers Paragraphs <p> </p> Paragraphs are the most rudimentary elements in a text document. <p>Serif typefaces have small slabs at the ends of letter strokes. In general, serif fonts can make large amounts of text easier to read.</p> <p>Sans-serif fonts do not have serif slabs; their strokes are square on the end. Helvetica and Arial are examples of sans-serif fonts. In general, sans-serif fonts appear sleeker and more modern.</p> Headings <h#> </h#> There are six levels of headings (h1 to h6). <h1>Top-Level Heading</h1> <p>This is a regular paragraph that will display at the browser's default font size and weight for comparison.</p> <h2>Second-Level Heading</h2> <h3>Third-Level heading</h3> <p>This is another paragraph for comparison. Of course, you can change the presentation of all of these elements with your own style sheets.</p> <h4>Fourth Level Heading</h4> <h5>Fifth Level Heading</h5> <h6>Sixth-Level Heading</h6> <p>This is another paragraph to show the default relationship of headings to body paragraphs. Of course, you can change the presentation of all of these elements with your own style sheets.</p> Headings (cont’d) h1 h2 h3 h4 h5 h6 Headings (cont’d) • Used to create the document outline. • Help with accessibility and search engine indexing. • Recommended to start with h1 and add subsequent levels in logical order. • Don’t choose headings based on how they look; use a style sheet to change them. Long Quotations (blockquotes) <blockquote> </blockquote> <p>Renowned type designer, Matthew Carter, has this to say about his profession:</p> <blockquote> <p>Our alphabet hasn't changed in eons; there isn't much latitude in what a designer can do with the individual letters.</p> <p>Much like a piece of classical music, the score is written down. It's not something that is tampered with, and yet, each conductor interprets that score differently. There is tension in the interpretation.</p> </blockquote> Preformatted Text <pre> </pre> Preformatted text preserves white space when it is important for conveying meaning. By default, pre text displays in a constant-width font, such as Courier. <pre> This is text with a an example of lot of curious whitespace. </pre> Line Breaks <br> The empty br element inserts a line break. <p>So much depends <br>upon <br><br>a red wheel <br>barrow</p> Thematic Breaks (Horizontal Rules) <hr> Indicates one topic has completed and another one is beginning. Browsers display a horizontal rule (line) in its place: <h3>Times</h3> <p>Description and history of the Times typeface.</p> <hr> <h3>Georgia</h3> <p>Description and history of the Georgia typeface.</p> Lists There are three types of lists in HTML: • Unordered lists • Ordered lists • Description lists Unordered Lists In unordered lists items may appear in any order (examples, names, options, etc.). Most lists fall into this category. <ul> </ul> Defines the whole list <li> </li> Defines each list item Unordered Lists (cont’d) <ul> <li>Serif</li> <li>Sans-serif</li> <li>Script</li> <li>Display</li> <li>Dingbats</li> </ul> You can change the appearance of the list dramatically with style sheet rules. Ordered Lists In ordered lists items occur in a particular order, such as step-bystep instructions or driving directions. <ol> </ol> Defines the whole list <li> </li> Defines each list item Ordered Lists (cont’d.) <ol> <li>Gutenberg develops moveable type (1450s)</li> <li>Linotype is introduced (1890s)</li> <li>Photocomposition catches on (1950s)</li> <li>Type goes digital (1980s)</li> </ol> Description Lists Description lists are used for any type of name/value pairs, such as terms/definitions, questions/answers, etc. <dl> </dl> Defines the whole list <dt> </dt> Defines a name, such as a term <dd> </dd> Defines a value, such as a definition Description Lists (cont’d) <dl> <dt>Linotype</dt> <dd>Line-casting allowed type to be selected, used, then recirculated into the machine automatically. This advance increased the speed of typesetting and printing dramatically.</dd> <dt>Photocomposition</dt> <dd>Typefaces are stored on film then projected onto photo-sensitive paper. Lenses adjust the size of the type.</dd> </dl> Page Organizing Elements HTML5 introduced elements that give meaning to the typical sections of a web page: • main • header • footer • section • article • aside • nav Main Content <main> </main> • Identifies the primary content of a page or application • Helps users with screen readers get to the main content of the page • Requires JavaScript workaround in Internet Explorer <body> <header>…</header> <main> <h1>Humanist Sans Serif</h1> …content continues… </main> </body> Headers and Footers <header> </header> <footer> </footer> header identifies the introductory material that comes at the beginning of a page, section, or article (logo, title, navigation, etc.). footer indicates the type of information that comes at the end of a page, section, or article (author, copyright, etc.) Headers and Footers (cont’d) <article> <header> <h1>More about WOFF</h1> <p>by Jennifer Robbins, <timedatetime="2017-11-11"> November 11, 2017</time></p> </header> <!-- ARTICLE CONTENT HERE --> <footer> <p><small>Copyright &copy;2017 Jennifer Robbins.</small></p> <nav> <ul> <li><a href="/">Previous</a></li> <li><a href="/">Next</a></li> </ul> </nav> </footer> </article> Sections <section> </section> section identifies thematic section of a page or an article. It can be used to divide up a whole page or a single article: <section> <h2>Typography Books</h2> <ul> <li>…</li> </ul> </section> <section> <h2>Online Tutorials</h2> <p>These are the best tutorials on the Web.</p> <ul> <li>…</li> </ul> </section> Articles <article> </article> article is used for self-contained works that could stand alone or be used in a different context (such as syndication). Useful for magazine/newspaper articles, blog posts, comments, etc. <article> <h1>Get to Know Helvetica</h1> <section> <h2>History of Helvetica</h2> <p>…</p> </section> <section> <h2>Helvetica Today</h2> <p>…</p> </section> </article> Aside (Sidebar) <aside> </aside> aside identifies content that is separate from but tangentially related to the surrounding content (think of it as a sidebar). <h1>Web Typography</h1> <p>Back in 1997, there were competing font formats and tools for making them…</p> <p>We now have a number of methods for using beautiful fonts on web pages…</p> <aside> <h2>Web Font Resources</h2> <ul> <li><a href="http://typekit.com/">Typekit</a></li> <li><a href="http://fonts.google.com">Google Fonts</a></li> </ul> </aside> Navigation <nav> </nav> nav identifies the primary navigation for a site or lengthy section or article. It provides more semantic meaning than a simple unordered list. <nav> <ul> <li><a <li><a <li><a <li><a <li><a </ul> </nav> href="/">Serif</a></li> href="/">Sans-serif</a></li> href="/">Script</a></li> href="/">Display</a></li> href="/">Dingbats</a></li> Inline Elements • Called text-level semantic elements in the spec. • Describe the types of elements that appear in the flow of text. a em strong q abbr cite dfn code var samp kbd sub/sup mark time data ins/del b i s u small bdi/bdo data span Inline Elements Emphasis <em> </em> Text that should be emphasized. Usually displayed in italics. <p><em>Arlo</em> is very smart.</p> <p>Arlo is <em>very</em> smart.</p> <strong></strong> Text that is important, serious, or urgent. Usually displayed in bold. <p>When returning the car, <strong>drop the keys in the red box by the front desk</strong>.</p> TIP: Use these elements semantically, not to achieve font styles. Think of how it would be read with a screen reader. Inline Elements Short Quotations <q> </q> For quoted phrases in the flow of text. Browsers add appropriate quotation marks automatically. <p>Matthew Carter says, <q>Our alphabet hasn't changed in eons.</q></p> Inline Elements Abbreviations and Acronyms <abbr> </abbr> The title attribute provides the long version of a shortened term, which is helpful for search engines and assistive devices. <abbr title="Points">pts.</abbr> <abbr title="American Type Founders">ATF</abbr> Inline Elements Superscript and Subscript <sup> </sup> <sub> </sub> Causes the selected text to display in a smaller size and slightly above (sup) or below (sub) the baseline. <p>H<sub>2</sub>0</p> <p>E=MC<sup>2</sup></p> Inline Elements Citations <cite> </cite> Identifies a reference to another document. <p>Passages of this article were inspired by <cite>The Complete Manual of Typography</cite> by James Felici.</p> Inline Elements Defining Terms <dfn> </dfn> Identifies the first and defining instance of a word in a document. There is no default rendering, so you need to format them using style sheets. <p><dfn>Script typefaces</dfn> are based on handwriting.</p> Inline Elements Code-Related Elements <code> </code> Code in the flow of text <var> </var> Variables <samp> </samp> Program sample <kbd> </kbd> User-entered keyboard strokes Inline Elements New Semantic Definitions for Old Presentational Inline Elements <b> </b> Phrases that need to stand out without added emphasis or importance (bold) <i> </i> (italic) Phrases in a different voice or mood than the surrounding text <s> </s> Text that is incorrect (strike-through) <u> </u> Underlined text, when underlining has semantic purpose <small> </small> Addendum or side note (smaller text size) Inline Elements Highlighted Text <mark> </mark> For phrases that may be particularly relevant to the reader (for example, when displaying search results): <p> ... PART I. ADMINISTRATION OF THE GOVERNMENT. TITLE IX. TAXATION. CHAPTER 65C. MASS. <mark>ESTATE TAX</mark>. Chapter 65C: Sect. 2. Computation of <mark>estate tax</mark>.</p> Inline Elements Dates and Times <time> </time> Provides machine-readable equivalents for dates and times. The datetime attribute specifies the date/time information in a standardized time format: <time datetime="1970-09-05T01:11:00">Sept.5, 1970, 1:11a.m.</time> Inline Elements Machine-Readable Information <data> </data> Helps computers make sense of content. The value attribute provides the machine-readable information. <data value="12">Twelve</data> <data value="978-1-449-39319-9">CSS: The Definitive Guide</data> Inline Elements Inserted and Deleted Content <ins> </ins> <del> </del> Markup for edits indicating parts of a document that have been inserted or deleted: Chief Executive Officer: <del title="retired">Peter Pan</del><ins>Pippi Longstocking</ins> Generic Elements <div> </div> Indicates division of content (generally block-level) <span> </span> Indicates a word or phrase • Generic elements are given semantic meaning with the id and class attributes. • They are useful for creating “hooks” for scripts and style rules. Div Example Use the div element to create a logical grouping of content or elements on the page. It indicates that they belong together in some sort of conceptual unit or should be treated as a unit by CSS or JavaScript. <div class="listing"> <img src="images/felici-cover.gif" alt=""> <p><cite>The Complete Manual of Typography</cite>, James Felici</p> <p>A combination of type history and examples of good and bad type design.</p> </div> Span Example Use the span element for text and other inline elements for which no existing inline element currently exists. In this example, a span is used to add semantic meaning to telephone numbers: <ul> <li>John: <span class="tel">999.8282</span></li> <li>Paul: <span class="tel">888.4889</span></li> <li>George: <span class="tel">888.1628</span></li> <li>Ringo: <span class="tel">999.3220</span></li> </ul> id and class Attributes id Assigns a unique identifier to the element. class Classifies elements into a conceptual group. Use the id attribute to identify. Use the class attribute to classify. NOTE: id and class can be used with all HTML elements. The id Attribute The value of an id attribute must be used only once in a document. Here it identifies a listing for a particular book by its ISBN: <div id="ISBN0321127307"> <img src="felici-cover.gif" alt=""> <p><cite>The Complete Manual of Typography</cite>, James Felici</p> <p>A combination of type history …</p> </div> Here it identifies a particular section of a document: <section id="news"> <!-- news items here --> </section> The class Attribute A class value may be used by multiple elements to put them in conceptual groups for scripting or styling. Here several book listings are classified as a “listing”: <div id="ISBN0321127307" class="listing"> … </div> <div id="ISBN0881792063" class="listing"> … </div> An element may belong to more than one class. Separate class values with character spaces: <div id="ISBN0321127307" class="listing book nonfiction"> Brief ARIA Introduction ARIA (Accessible Rich Internet Applications) is a standardized set of attributes for making pages easier to navigate and use with assistive devices. ARIA defines roles, states, and properties that developers can add to markup and scripts to provide richer information. www.w3.org/TR/html-aria ARIA Roles Roles describe or clarify an element’s function in the document. Examples: alert, button, dialog, slider, and menubar <div id="status" role="alert">You are no longer connected to the server.</div> ARIA States and Properties • ARIA defines a long list of states and properties that apply to interactive elements and dynamic content. • Properties values are likely to be stable (example: aria-labelledby). • States have values that are likely to change as the user interacts with the content (example: aria-selected). Escaping Characters Escaping a character means representing it by its named or numeric character entity in the source. • Some characters must be escaped because they will be mistaken for code (example: the < character would be parsed as the start of an HTML tag). • Some characters are invisible or just easier to escape than find on the keyboard. Character Entity References Character entities always begin with & and end with ;. Named entities Use a predefined name for the character (example: &lt; for the less-than symbol <) Numeric entities Use an assigned numeric value that corresponds to its position in a coded character set, such as UTF-8 (example: &#060; for the less-than symbol <). A complete list of HTML named entities and their Unicode code-points is at www.w3.org/TR/html5/syntax.html#named-character-references. Escaping HTML Syntax Characters Always escape <, >, and & characters in content. Escape " and ' when they are in attribute values. Decimal Hexadecimal &gt; &#062; &#x3E; Quote &quot; &#160; &#x22; ' Apostrophe &apos; &#039; &#x27; & Ampersand &amp; &#038; &#x26; Character Description Entity name < Less-than symbol &lt; > Greater-than symbol " (Additional non-required character entities are listed in Chapter 5.) 6 ADDING LINKS OVERVIEW • The a element • External links with absolute URLs • Links with relative pathnames • Linking within a page (fragments) • Targeting browser windows • Mail links Adding Links <a> </a> <a href="URL">Link text or image</a> The href attribute provides the location (URL) of the resource. You can link to any resource: • HTML documents • Images • Movies • PDFs • More! href Attributes • Absolute URLs begin with the protocol (ex: http://). • Relative URLs provide the path to a file on the same server as the document containing the link (ex: /directory/document.html). • Long URLs can make the markup look complicated, but the structure is the same: External Links • External links go to pages that are not on your server. • An absolute URL is required, including “http://” <li><a href="http://www.foodnetwork.com">The Food Network</a></li> Linking on Your Own Site • When no protocol is provided, the browser looks on the current server for the resource. • A relative pathname describes how to get to the resource starting from the current document. • Pathnames follow UNIX syntax conventions. Example Server Directory Structure The following relative pathname discussions are based on this site structure. The root directory is called jenskitchen. How it looks in the MacOS Finder Linking in the Same Directory When the linked document is in the same directory as the current document, just provide its filename: href="about.html" Linking into a Lower Directory If the linked file is in a directory, include the directory name in the path. href="recipes/salmon.html" Linking into Two Directories Include each subdirectory name in the path to the linked document: href="recipes/pasta/couscous.html" Linking to a Higher Directory To back up a level, the ../ stands in for the name of the higher directory: href="../index.html" Linking Up Two Directory Levels Include a ../ for each level you need to back up to: href="../../index.html" Site Root Relative Paths Starting the path with a slash / means the pathname starts at the root directory. You don’t need to write the name of the directory. href="/recipes/salmon.html” NOTE: Site root relative URLs are more flexible because they work from any document on the site. DOWNSIDE: They won’t work on your own computer because the / will be relative to your hard drive. You’ll need to test it on the actual web server. Image src Pathnames Relative pathnames are also commonly used to point to image files with the src attribute: <img src="/images/icons/next.svg" alt="next"> Linking Within a Page (Fragments) Linking to a specific point on a web page is called linking to a document fragment. This is useful for providing links down to content from the top of a long document. Linking to a Fragment For example, to create a link from the letter H in a list at the top of the page to the “H” heading farther down in the document: Step 1: Identify the target destination. Use the id attribute to give the target element a unique name: <h2 id="startH">H</h2> Step 2: Link to the target (#). The # symbol before the name indicates that the link goes to a fragment: <p>… F | G | <a href="#startH">H</a> | I | … </p> Targeting Browser Windows The target attribute in the a tag tells the browser the name of the window in which you want the linked document to open: <a href="recipes.html" target="_blank">Recipe book</a> target="_blank" Always opens a new browser window. target="name" Opens a new window with that name and then opens all subsequent targeted links with that name in the same window. It may also open in an embedded frame (iframe) with that name. Mail Links Use the “mailto” protocol to make a linked email address open in a mail program: <a href="mailto:wonderwoman@example.com">Email WonderWoman</a> (wonderwoman@example.com) NOTE: Most browsers are configured to open the computer’s primary email program, but this may not work for some users. Be sure the email address is included on the page and use the mailto link as progressive enhancement. 7 ADDING IMAGES OVERVIEW • Web image formats • The img element • Attributes for the img element • Adding an SVG to a page Web Image Formats Image formats appropriate for web pages: • PNG • JPEG • GIF • SVG • WebP (up and coming, not yet widely supported) Bitmapped vs. Vector Formats PNG, JPEG, GIF, and WebP are bitmapped formats. SVG is a vector format. The img Element <img src="" alt=""> • Embed images on the page with the empty img element. • The src and alt attributes are required. • img can be used for PNG, JPEG, GIF, and SVG. NOTE: Special markup is recommended for experimenting with cuttingedge image formats like WebP. The img Element (cont’d) The img element tells the browser to make a server request for the image and display it in its place: <p>This summer, try making pizza <img src="pizza.png" alt=""> on your grill.</p> The src attribute <img src="/images/icon/next.png" alt="Next"> • The value is the location (URL) of the image file. • Use the relative pathname conventions to point to the image on the server. PERFORMANCE TIP: Take advantage of caching (temporary storage). For the same image used repeatedly, using the same pathname reduces the number of calls to the server. The alt Attribute <p> If you're <img src="/images/smiley.png" alt="happy"> and you know it, clap your hands.</p> • The alt attribute provides alternative text for those who are not able to see it. • It is required for every img element in order for the HTML to be valid. • It is used by screen readers, search engines, and graphical browsers when the image fails to load. Alternative Text Tips • Alternative text (alt text) should convey the same information and function as the image. • If the image is purely decorative and shouldn’t be read aloud, include the alt attribute with an empty value: <img src="flowers.svg" alt=""> • Consider what the alt text would sound like when read aloud by a screen reader. Is it helpful or a hindrance? • When an image is used as a link, the alt text serves as the linked text. Write what you’d want the link to say, don’t just describe the image. • Avoid starting alt text with “An image of” or “Graphic of”. width and height Attributes <img src="flowers.svg" alt="" width="120" height="160"> • The width and height attributes set the dimensions of the image on the page in number of pixels. • They help the browser maintain space for the image in the layout while the files load. • Don’t use width and height attributes if you are sizing the image with style sheets or if the size changes in a responsive layout. • If the attribute values do not match the dimensions of the image, the image will resize and may be distorted or blurry. Adding SVG Images SVG images are unique: • SVG is a vector format, made up of shapes and paths. • Those shapes and paths are described in a text file using the Scalable Vector Graphic markup language. • The elements in an SVG can be styled with CSS and scripted for interactivity. • Because they are vector, SVGs can resize with no loss of quality. SVG Example Compare the SVG source to the image. The svg element contains a rectangle (rect element) and a text element: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 180"> <rect width="300" height="180" fill="purple" rx="20" ry="20"/> <text x="40" y="114" fill="yellow" font-family="'Verdana-Bold'" font-size="72"> hello! </text> </svg> Adding SVG to a Page There are several ways to add an SVG image to a web page: • <img> element • <object> element • <svg> element directly in HTML (inline SVG) Adding SVG with the img Element You can add an .svg file to the page with the img element: <img src="/images/circle.svg" alt=""> PROS: • Easy and familiar • Universally supported CONS: • Can’t manipulate the SVG with scripts or styles. • The SVG can’t contain any external resources such as images or fonts. Embedding SVGs with object The content of the object element is a fallback text or image that displays if the SVG is not supported: <object type="image/svg+xml" data="pizza.svg"> <img src="pizza.png" alt="pizza"> </object> PROS: • SVG can be scripted and use eternal files (images and fonts). CONS: • You can’t change styles with the same CSS used for the document. • May be buggy in some browsers. Inline SVGs with the svg Element You can paste the content of the SVG text file directly into the HTML source. This is called using the SVG inline. PROS: • Can take full advantage of scripting and styling the SVG because the elements in the SVG are part of the DOM for the document. CONS: • Code can get extremely long and unwieldy. • Harder to maintain images embedded in the source • Can’t take advantage of caching repeated images • Not universally supported Example of an Inline SVG <p>This summer, try making pizza <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72" width="100" height="100"> <circle fill="#D4AB00" cx="36" cy="36" r="36"/> <circle opacity=".7" fill="#FFF" stroke="#8A291C" cx="36.1" cy="35.9" r="31.2"/> <circle fill="#A52C1B" cx="38.8" cy="13.5" r="4.8"/> <circle fill="#A52C1B" cx="22.4" cy="20.9" r="4.8"/> <circle fill="#A52C1B" cx="32" cy="37.2" r="4.8"/> <circle fill="#A52C1B" cx="16.6" cy="39.9" r="4.8"/> <circle fill="#A52C1B" cx="26.2" cy="53.3" r="4.8"/> <circle fill="#A52C1B" cx="42.5" cy="27.3" r="4.8"/> <circle fill="#A52C1B" cx="44.3" cy="55.2" r="4.8"/> <circle fill="#A52C1B" cx="54.7" cy="42.9" r="4.8"/> <circle fill="#A52C1B" cx="56" cy="28.3" r="4.8"/> </svg> on your grill.</p> 7B RESPONSIVE IMAGE MARKUP OVERVIEW • How responsive images work • High-density displays • Variable-width images • Art direction with the picture element • Alternative image types About Responsive Images Responsive image markup allows us to deliver images that are appropriate for the user’s viewing environment. How it works: • You provide multiple image versions. • You specify sizes and preferences with responsive image markup. • The browser makes the final selection. About Responsive Images (cont’d) Responsive image markup addresses four scenarios: • Sending larger images to high-density screens • Sending a variety of image sizes for different screen sizes • Sending alternately cropped images for small screens (art direction) • Providing alternative image formats with smaller file sizes to supporting browsers High-Density Displays (x-descriptor) • Screens and images are made up of squares of colored light called pixels. T • On standard screens, the pixels in an image and CSS measurements map one-to-one with the device pixels. • High-density displays fit 2x, 3x, or 4x the number of device pixels in the same amount of space. • High-density devices use a measurement called reference pixels for page layout. Images and CSS measurements map with the reference pixel grid (not the tiny device pixels). High-Density Displays (cont’d) High-Density Displays (cont’d) In order for images to look sharp and not blurry on high-density displays, they need to map with the device pixels. Example: For an image that displays at 200 pixels wide in the layout, provide these versions: • 200px wide image for standard screens • 400px wide image for 2x high-density screens • 600px wide image for 3x high-density screens • 800px wide image for 4x high-density screens High-Density Displays (cont’d) The srcset attribute in the img element lists image alternatives based on pixel density, specified with an x-descriptor (#x): <img src="/images/photo-200px.jpg" alt="" srcset="/images/photo-400px.jpg 2x, /images/photo-600px.jpg 3x" > • The src attribute is required. Use it for the standard image. • The srcset value is a comma-separated list of alternative image URLs followed by an x-descriptor. • A device with a standard screen density gets only the 200px wide version of the image. Higher densities get larger images. High-Density Displays (cont’d) X-descriptors tell the browser to make an image selection based on screen resolution only. Use x-descriptors for images that stay the same pixel dimensions regardless of the screen size and layout changes. Variable-Width Images (w-descriptor) When images resize based on the size of the screen or browser window (such as in a responsive layout). Use the srcset attribute with a w-descriptor and the sizes attribute to make a viewportbased selection: Variable-Width Images (cont’d) <img src="strawberries-640.jpg" alt="baskets of ripe strawberries" srcset="strawberries-480.jpg 480w, strawberries-960.jpg 960w, strawberries-1280.jpg 1280w, strawberries-2400.jpg 2400w" sizes="100vw"> • The src attribute is required and specifies the default image size. • The value of srcset is a comma-separated list of images and wdescriptors. • w-descriptors list the actual image width (in pixels). • The sizes attribute specifies the size at which the image appears in the layout. In this example, it is 100% the width of the browser (100 viewport-width units). Variable-Width Images (cont’d) If the image proportion changes based on the size of the viewport, use a media condition in the sizes attribute to test for the screen width and determine the image size: sizes = (media-feature: condition) length Variable-Width Images (cont’d.) <img src="strawberries-640.jpg" alt="baskets of ripe strawberries" srcset="strawberries-240.jpg 240w, strawberries-480.jpg 480w, strawberries-672.jpg 672w" sizes="(max-width: 480px) 100vw, (max-width: 960px) 70vw, 240px"> • If the viewport is 480 pixels or less, the image fills 100% of the viewport width. • If the viewport is wider than 480 pixels but less than 960 pixels (maxwidth: 960px), the image appears at 70% of the viewport width. • If the viewport is wider than 960 pixels, the image gets sized to exactly 240 pixels. • Now that the browser knows the width of the viewport and how big the image will appear within it, it can select the most appropriate image from the srcset list to download. Art Direction Selection (picture element) Details may be lost in images scaled down to fit small screens. To change the image itself rather than just resizing it, make an artdirection-based selection with the picture and source elements: • Provide differently cropped versions. • Provide both landscape (wide) and portrait (tall) versions. • Change or remove text in images to keep it legible. Art Direction Selection (cont’d) Art Direction Selection (cont’d) <picture> <source media="(min-width: 1024px)" srcset="icecream-large.jpg"> <source media="(min-width: 760px)" srcset="icecream-medium.jpg"> <img src="icecream-small.jpg" alt="hand holding ice cream cone and text that reads Savor the Summer"> </picture> • The picture element has no attributes; it is a wrapper for source and img elements. • The img element is required and must go last in the list. • source elements test for media conditions (media attribute) and provide alternative image options for each size (srcset). Alternative Image Formats (type Attribute) • New, efficient image formats (WebP, JPEG 2000, and JPEG XR) are available, but aren’t supported by every browser. • Use the picture and source elements with the type attribute for image-format-based selections: <picture> <source type="image/webp" srcset="pizza.webp"> <source type="image/jxr" srcset="pizza.jxr"> <img src="pizza.jpg" alt=""> </picture> • Browsers use the first image format they support and don’t download the rest. Browser Support • picture, source, srcset, and sizes are supported by all current browser versions. • Every technique includes a standards img element as a reliable fallback. • For better support, use the Picturefill polyfill script that makes older browsers support the new markup (scottjehl.github.io/picturefill). 8 TABLE MARKUP OVERVIEW • How tables are structured • Table headers • Cell spanning (rows and columns) • Table captions • Row and column groups Tabular Data HTML table markup is for data arranged into rows and columns. HTML Table Structure Tables are made up of cells arranged into rows. A simple table HTML Table Structure (cont’d.) How it looks using markup (table, tr, th, and td): NOTE: Columns are implied by the number of cells in each row (not created with column elements). HTML Table Structure (cont'd) The same table written in code: <table> <tr> <th>Menu item</th> <th>Calories</th> <th>Fat (g)</th> </tr> <tr> <td>Chicken noodle soup</td> <td>120</td> <td>2</td> </tr> <tr> <td>Caesar salad</td> <td>400</td> <td>26</td> </tr> </table> Default browser display: The table Element <table> </table> • Identifies tabular material • Contains some number of row (tr) elements • Optionally, may also have a caption element and row and column group elements Table Row (tr) Element <tr> </tr> • tr stands for “table row.” • The only thing that can go between tr tags is some number of th (header) and td (data cell) elements. • There may be no text content in a row that is not contained within a header or data cell. Table Cells <td> </td> • td stands for “table data.” • Cells can contain any type of web content. • All content in a table must be contained in td tags. Table Headers <th> </th> • th stands for “table header.” • Headers provide information about the cells in the row or column they precede. • They are key tools for making table content accessible. Screen readers may read headers aloud before each data cell, providing context that is missing when you can’t see the table. • Headers are often rendered in a bold font by default. Table Columns Are Implied This table would have 2 rows and 3 columns (because there are 3 cells defined in each row): <table> <tr> <th>Burgers</th> <td>Organic Grass-fed Beef</td> <td>Black Bean Veggie</td> </tr> <tr> <th>Fries</th> <td>Hand-cut Idaho potato</td> <td>Seasoned sweet potato</td> </tr> </table> Spanning Cells Spanning Stretching a cell to cover several rows or columns Column span Stretching a cell to the right over subsequent columns Row span Stretching a cell downward over several rows Column Spans Use the colspan attribute to specify the number of columns the cell should span over: <table> <tr> <th colspan="2">Fat</th> </tr> <tr> <td>Saturated Fat (g)</td> <td>Unsaturated Fat (g)</td> </tr> </table> Notice that the first tr element only has one cell in it now. Every row should have the same number of cells or equivalent colspan values. Row Spans The rowspan attribute to specifies the number of rows the cell spans: <table> <tr> <th rowspan="3">Serving Size</th> <td>Small (8oz.)</td> </tr> <tr> <td>Medium (16oz.)</td> </tr> <tr> <td>Large (24oz.)</td> </tr> </table> Notice that the td elements that were spanned over are no longer in the source. Table Caption <caption> </caption> • Provides a title or description for the table • Improves table accessibility • The caption element must appear first in the table element. • The caption displays above the table by default. Table Caption (cont’d) <table> <caption>Nutritional Information</caption> <tr> <th>Menu item</th> <th>Calories</th> <th>Fat (g)</th> </tr> …table continues… </table> Row and Column Groups • For complicated tables, you can create semantic groups of rows and/or columns that describe the table’s structure. • Row group and column group elements also provide more “hooks” for scripting and styling. Row Groups <thead> </thead> <tbody> </tbody> <tfoot> </tfoot> • Provide additional semantic structure • Row group elements may contain one or more tr elements (no direct text content). • Some browsing agents may repeat the header and footer rows on tables that span multiple pages. Row Groups (cont’d) <table> … <thead> <!-- headers --> <tr></tr> <tr></tr> <tr></tr> <thead> <tbody> <!-- data --> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> <tr></tr> </tbody> <tfoot> <!-- footnote --> <tr></tr> </tfoot> </table> NOTE: this table also utilizes row and column spans. Column Groups <colgroup> </colgroup> <col> </col> • Allows you to assign id and class names to columns so they can be accessed by scripts or styles • colgroup elements go at the start of the table, after the caption element if there is one. • colgroup elements contain no content; they only provide an indication of column structure Column Groups (cont’d) The number of columns in a group is noted with the span attribute: If you need to access individual columns, identify them with col elements: <table> <caption>…</caption> <colgroup></colgroup> <colgroup span="2"></colgroup> <colgroup span="2"></colgroup> <!-- rest of table... --> <colgroup></colgroup> <colgroup> <col class="start"> <col class="end"> </colgroup> <colgroup> <col class="start"> <col class="end"> </colgroup> 9 FORMS OVERVIEW • How forms work • Menus • The form element • Specialized inputs • Text entry controls • Form accessibility • Buttons • Form design tips How Forms Work Web forms have two components: • The form on the page that collects input • An application on the server that processes the collected information Web Form Transaction 1. Browser renders the form inputs as indicated in the markup. 2. User enters information in the form and hits Submit. 3. The browser encodes the information entered and sends it to the server. 4. The application processes the information. 5. The application returns a response (for example, a thank you message or reloading the page). Web Processing Applications Web forms may be processed by any of the following technologies: • PHP (.php) • Microsoft ASP (.asp) • Microsoft ASP.net (.aspx) • Ruby on Rails • JavaServer Pages (.jsp) • Python The form Element <form action="URL" method="POST or GET"> <!-- Form content and inputs here --> </form> • The form element is a container for all the content in the form and its input controls. • The action and method attributes are necessary for interacting with the processing program. The action Attribute <form action="mailinglist.php" method="POST"> The action attribute provides the location of the script or application that will process the collected form data. The method Attribute <form action="mailinglist.php" method="POST"> The method attribute specifies how the encoded information should be sent to the server (GET or POST): • GET: The encoded data is tacked onto the URL sent to the server: get http://www.bandname.com/mailinglist.php?name=Sally%20Strong arm&email=strongarm%40example.com • POST: Data is send in a separate transaction and can be encrypted with HTTPS. NOTE: POST is the most common method. Form Control Elements Form control elements (also called widgets) collect data from the user. A few examples: <input type="text"> <input type="submit"> <input type="checkbox"> <select> Form Control Elements (cont’d) Form controls collect data in variable/value pairs. Examples: variable = "email" value = jen@example.com variable = "color" value = green Variables (the name Attribute) • A variable is a bit of information collected by a form control (example: the user’s last name). • The required name attribute in the control element provides the name of the variable for that control: <input name="lastname"> NOTE: The variable name is also programmed into the web processing script or app, so the name in the markup must match the name in the processor. Values • The data entered or selected by the user in the form control is the value that gets sent to the server. It is paired with the variable for that control. • You can provide a default value with the value attribute: Name: <input name="lastname" value="Unknown"> In this example, if the text input is left blank, the value “Unknown” would be sent to the server for the variable “lastname”. FORM CONTROL ELEMENTS Text Entry Input <input type="text"> <input type="text" name="color" value="Red" maxlength="24"> type: Type of input control, in this case a single-line text field name: Required variable name value: Default text that appears in the field and is sent to server if the field is left blank maxlength, minlength: Sets a character limit for the field size: The length of the field in number of characters (CSS is more common for sizing) FORM CONTROL ELEMENTS Password Field <input type="password"> <input type="password" name="pswd" maxlength="10"> • Like a text entry field, except the characters are obscured from view • The data entered is not encrypted on the way to the server (unless it uses HTTPS, a secure web protocol). FORM CONTROL ELEMENTS Multi-line Text Entry <textarea> </textarea> <textarea name="entry" rows="6" cols="64">This band is totally awesome!</textarea> The content of the textarea element is the default value. rows: The number of rows tall the field is initially drawn (users can write more) cols: Width of initial text field, in number of characters maxlength, minlength: Limits the number of characters that can be entered FORM CONTROL ELEMENTS Specialized Text Entry Fields <input <input <input <input type="search"> type="email"> type="tel"> type="url"> • These input types are more semantically rich than a default text field. • Browsers may provide keyboards tailored to the input type. • Browsers may validate entries on the fly without using the server application. Specialized Text Entries (cont’d) <input type="tel" name=""> <input type="email" name=""> Numerical keyboard provided on iOS Opera looks for email address structure FORM CONTROL ELEMENTS Submit and Reset Buttons <input type="submit"> • Submits the collected form data to the server. Does not require a variable name (name attribute): <input type="reset" value="Start over"> • Resets the form to its defaults • Less common with the rise of JavaScript for form handling • Change the button text with the value attribute. FORM CONTROL ELEMENTS Custom Buttons <button> </button> The button element is used for creating custom buttons with JavaScript. <input type="button"> Creates a custom button that has no predefined function and can be customized with JavaScript <input type="image" alt=""> Allows an image to be used as a button to replace the Submit button. It requires a descriptive alt attribute value. FORM CONTROL ELEMENTS Radio Buttons <input type="radio"> Only one radio button may be selected at a time. <p>How old are you?</p> <ol> <li><input type="radio" <li><input type="radio" <li><input type="radio" <li><input type="radio" </ol> name="age" name="age" name="age" name="age" value="under24" checked> under 24</li> value="25-34"> 25 to 34</li> value="35-44"> 35 to 44</li> value="over45"> 45+</li> NOTE: You can’t belong to more than one age group, so radio buttons are the right choice for this list. Radio Buttons (cont’d.) <input type="radio" value=""> • Applying the same variable name to input elements binds them together as a mutually exclusive set of options. • The value for each button must be provided with the value attribute. • The checked attribute causes an option to be selected when the page loads. Only one input may be checked. FORM CONTROL ELEMENTS Checkbox Buttons <input type="checkbox"> Multiple checkbox buttons may be selected. <p>What type <ul> <li><input <li><input <li><input <li><input </ul> of music do you listen to?</p> type="checkbox" type="checkbox" type="checkbox" type="checkbox" name="genre" name="genre" name="genre" name="genre" value="punk" checked> Punk rock</li> value="indie" checked> Indie rock</li> value="hiphop"> Hip Hop</li> value="rockabilly"> Rockabilly</li> NOTE: You can like more than one type of music, so checkbox buttons are the right choice for this list. Checkbox Buttons (cont’d) <input type="checkbox" value=""> • Applying the same variable name to input elements binds them together as a group. • The value for each button must be provided with the value attribute. • The checked attribute causes an option to be selected when the page loads. Multiple buttons in a group may be checked. FORM CONTROL ELEMENTS Drop-down Menus <select> </select> <option> </option> <optgroup> </optgroup> • The select element creates a drop-down menu when there is no size attribute (or if size="1"). • The select element contains some number of option elements. • The content of the option element is the value sent to the server (or one can be provided with the value attribute). Drop-down Menus (cont’d.) The select menu drops down to reveal options when the user clicks on it. <p>What is your favorite 80s band? <select name="EightiesFave"> <option>The Cure</option> <option>Cocteau Twins</option> <option>Tears for Fears</option> <option>Thompson Twins</option> <option value="EBTG">Everything But the Girl</option> <option>Depeche Mode</option> <option>The Smiths</option> <option>New Order</option> </select> </p> FORM CONTROL ELEMENTS Scrolling Menus <p>What is your favorite 80s band? <select name="EightiesFave" size="6" multiple> <option>The Cure</option> ... </select> </p> • The same markup as drop-down menus, but the size attribute specifies how many lines to display. • The multiple attribute allows more than one option to be selected. Scrolling Menus (cont’d) Use the optgroup element to create a conceptual group of options. The label attribute provides the the heading for the group: <select name="icecream" size="7" multiple> <optgroup label="traditional"> <option>vanilla</option> <option>chocolate</option> </optgroup> <optgroup label="fancy"> <option>Super praline</option> <option>Nut surprise</option> <option>Candy corn</option> </optgroup> </select> FORM CONTROL ELEMENTS File Upload Control <input type="file"> <form action="/client.php" method="POST" enctype="multipart/form-data"> <label>Send a photo to be used as your online icon <em>(optional)</em><br> <input type="file" name="photo"></label> </form> • The file input type allows a user to select a document from their hard drive to be submitted with the form data. • The method must be set to POST, and the encoding type must be included. FORM CONTROL ELEMENTS Hidden Control <input type="hidden"> <input type="hidden" name="success-link" value="http://www.example.com/thankyou.html"> • Sometimes it is necessary to feed values to the processing script/app that don’t come from the user. • Hidden controls don’t display in the browser. FORM CONTROL ELEMENTS Date and Time Controls <input <input <input <input <input type="date"> type="time"> type="datetime-local"> type="month"> type="week"> <input type="date" name="birthday" value="2017-01-14"> A starting value may be provided in standard date-time format. Date and Time Controls (cont’d) Browsers may display date and time selection widgets (not universally supported). On non-supporting browsers, date and time inputs display as usable text-entry fields. FORM CONTROL ELEMENTS Numerical Controls <input type="number"> <input type="range"> Number and range controls collect numerical data. Browsers may render counter or slider widgets. Both types accept min and max attributes for setting limits on the allowed values. FORM CONTROL ELEMENTS Color Selector <input type="color"> The color input type is intended to provide a pop-up color picker. It is not well supported. Nonsupporting browsers display a text-entry field. Form Accessibility • Users may not be able to see the form. They may be listening to it with a screen reader. • Whereas sighted users can see at a glance how elements are organized, form accessibility features create semantic connections between form components. FORM ACCESSIBILITY Labels <label> </label> The label element associates a descriptive label with a form field. Implicit association The label text and form control are both contained within the label element: <li><label>Red <input type="radio" name="color" value="red"></label></li> Explicit association Matches the label with the control's ID reference using the for attribute: <li><label for="form-colors-red">Red</label> <input type="radio" name="color" value="red id="form-colors-red"></li> FORM ACCESSIBILITY Fieldsets and Legends <fieldset> </fieldset> <legend> </legend> fieldset Indicates a logical grouping of controls (examples: credit card name, number, date, etc.). By default, rendered with a box around the set of controls. legend Provides a caption for the enclosed fields. By default, it’s displayed along the top edge of the fieldset. Fieldsets and Legends (cont’d) <fieldset> <legend>Customer Information</legend> <ul> <li><label>Full name: <input type="text" name="fullname"></label></li> <li><label>Email: <input type="text" name="email"></label></li> <li><label>State: <input type="text" name="state"></label></li> </ul> </fieldset> Form Design Tips • Avoid unnecessary questions. • Consider the impact of label placement. Labels above fields tend to lead to faster completion. • Choose input types carefully. • Group related inputs. • Primary actions (e.g., “Buy”) should be visually dominant to secondary actions (e.g., “Back”). 10 EMBEDDED MEDIA OVERVIEW • iframes • Generic object element • Video players • Audio players • Canvas Window-in-a-Window (iframe) <iframe> </iframe> • The iframe element lets you embed a separate HTML document on a page. • It displays in its own window-in-a-window (called a nested browsing context). • Commonly used to embed videos, maps, and advertising iframe (cont’d) <h1>An Inline Frame</h1> <iframe src="glossary.html" width="400" height="250"> Your browser does not support inline frames. Read the <a href="glossary.html">glossary</a>. </iframe> • The content of the iframe element is a fallback that displays if iframe is not supported. • The width and height attributes specify the size of the window in pixels. The object Element <object> </object> <param> </param> <object data="picture.svg" type="image/svg+xml"> <img src="picture.png" alt=""> </object> • A generic element for embedding media on a web page. The media may require a plug-in to run. • The data attribute points to the media file. • The type attribute is the type of media (its MIME type). • The content of the object element is a fallback if the media type isn’t supported. The object Element (cont’d) <object type="video/quicktime" data="movies/hekboy.mov" width="320" height="256"> <param name="autostart" value="false"> <param name="controller" value="true"> </object> Some media formats may require that the object contain a number of param elements that set parameters specific to that type of media. Example: Starting a video automatically or displaying player controls Embedded Video <video> </video> HTML5 introduced the video element for embedding a video player on a web page. There is also an API for controlling video play. <video src="windtunnel.mp4" width="320" height="262" poster="windtunnel_still.jpg" controls autoplay> Get the <a href="windtunnel.mp4">MP4 wind tunnel video</a> </video> Embedded Video (cont’d.) The content in the video element is a fallback for browsers that don’t support the HTML5 video element (e.g., providing a link to the video). video element attributes: • width/height: Specific dimension in pixels • poster: Provides location of still image to show before video plays • controls: Indicates that the video player controls should be visible • autoplay: Makes the video start playing automatically Video Formats • Browsers are inconsistent about which video formats they support (see table). • Best supported format: MP4 (H.264) [MPEG-4 video container, H.264 video compression, and AAC audio compression] Format Type IE MS Edge Chrome Firefox Safari Opera Android Brows er iOS Safar i MP4 (H.264) video/mp4 mp4 m4v 9.0+ 12+ 4+ Yes* 3.2+ 25+ 4.4+ 3.2+ WebM (VP8) video/webm webm webmv – – 6+ 4.0+ – 15+ 2.3+ – WebM (VP9) video/webm webm webmv – 14+ 29+ 28+ – 16+ 4.4+ – Ogg Theora video/ogg ogv – – 3.0+ 3.5+ – 13+ 2.3+ – Video Formats (cont’d.) <source> </source> To provide several video format options, list them in source elements in the video element. The browser downloads the first file it supports, so put the videos with the smallest file sizes first. <video id="video" controls poster="img/poster.jpg"> <source src="clip.webm" type="video/webm"> <source src="clip.mp4" type="video/mp4"> <source src="clip.ogg" type="video/ogg"> <a href="clip.mp4">Download the MP4 of the clip.</a> </video> Audio Players <audio> </audio> <source> </source> The audio element embeds an audio player on the page, similar to video, but with no height, width, or poster attributes: <audio id="threeoclock" controls preload="auto"> <source src="jetfighter.mp3" type="audio/mp3"> <source src="jetfighter.ogg" type="audio/ogg"> <source src="jetfighter.webm" type="audio/webm"> <p>Download <a href="jetfighter.mp3">"Jet Fighter"</a></p> </audio> Audio Formats • Browsers are inconsistent in audio format support (see table). • Best supported format: MP3 Format Type IE MP3 audio/mpeg mp3 9.0+ WAV audio/wav or audio/wave – MS Edge Chrome Firefox Opera Safari iOS Safari Android 12+ 3.0+ 22+ 15+ 4+ 12+ 8.0+ 3.5+ 11.5 4+ 3.2+ 2.3+ – – 2.3+ 4.1 2.3+ + Ogg audio/ogg ogg oga – – 4.0+ 3.5+ Vorbis MPEG- + audio/mp4 m4a 11.0 4/AAC WebM/Vo 12+ 12.0+ – 15+ 4+ 4.1+ 3.0+ – 6.0+ 4.0+ 11.5 – – 2.3.3+ – – – + audio/webm webm – rbis WebM/O 11.5 + audio/webm webm – 14+ 33+ 15+ 20+ pus Adding Text Tracks <track> </track> The track element provides text that is synchronized with the audio or video. Useful for: • Subtitles • Captions • Descriptions for sight impaired • Chapter titles • Metadata (non-displaying) Adding Text Tracks (cont’d.) The track element goes inside the video or audio element you want to annotate. The src attribute points to a text file in .vtt format. <video width="640" height="320" controls> <source src="japanese_movie.mp4" type="video/mp4"> <source src="japanese_movie.webm" type="video/webm"> <track src="english_subtitles.vtt" kind="subtitles" srclang="en" label="English subtitles" default> <track src="french.vtt" kind="subtitles" srclang="fr" label="Sous-titres en français"> </video> Canvas <canvas> </canvas> • The canvas element embeds a 2-D bitmapped drawing area that is controlled by JavaScript functions. • It is useful for games and drawing interfaces. muro.deviantart.com majong.frvr.com Canvas (cont’d) A sample of the JavaScript used to draw this simple graphic. //draw face my_canvas.beginPath(); my_canvas.arc(100, 100, 75, (Math.PI/180)*0, (Math.PI/180)*360, false); // circle dimensions my_canvas.strokeStyle = "black"; // circle outline is black my_canvas.lineWidth = 3; // outline is three pixels wide my_canvas.fillStyle = "yellow"; // fill circle with yellow my_canvas.stroke(); // draw circle my_canvas.fill(); // fill in circle my_canvas.closePath(); 11 INTRODUCING CSS OVERVIEW • The benefits of CSS • Inheritance • Understanding document structure • The cascade • The box model • CSS units of measurement • • Writing style rules Attaching styles to the HTML document The Benefits of CSS • Precise type and layout control • Less work: Change look of the whole site with one edit • Accessibility: Markup stays semantic • Flexibility: The same HTML markup can be made to appear in dramatically different ways Style Separate from Structure These pages have the exact same HTML source but different style sheets: (csszengarden.com) How Style Sheets Work 1. Start with a marked up document (like HTML, but could be another XML markup language). 2. Write styles for how you want elements to look using CSS syntax. 3. Attach the styles to the document (there are a number of ways). 4. The browser uses your instructions when rendering the elements. Style Rules Each rule selects an element and declares how it should display. h1 { color: green; } This rule selects all h1 elements and declares that they should be green. strong { color: red; font-style: italic; } This rule selects all strong inline elements and declares that they should be red and in an italic font. Style Rule Structure • A style rule is made up of a selector a declaration. • The declaration is one or more property / value pairs. Selectors There are many types of selectors. Here are just two examples: p {property: value;} Element type selector: Selects all elements of this type (p) in the document. #intro {property: value} ID selector (indicated by the # symbol) selects by ID value. In the example, an element with an id of “intro” would be selected. Declarations The declaration is made up of a property/value pair contained in curly brackets { }: selector { property: value; } Example h2 { color: red; font-size: 2em; margin-left: 30px; opacity: .5; } Declarations (cont’d) • End each declaration with a semicolon to keep it separate from the next declaration. • White space is ignored, so you can stack declarations to make them easier to read. • Properties are defined in the CSS specifications. • Values are dependent on the type of property: • Measurements • Keywords • Color values • More CSS Comments /* comment goes here */ • Content between /* and */ will be ignored by the browser. • Useful for leaving notes or section labels in the style sheet. • Can be used within rules to temporarily hide style declarations in the design process. Adding Styles to the Document There are three ways to attach a style sheet to a document: External style sheets A separate, text-only .css file associated with the document with the link element or @import rule Embedded style sheets Styles are listed in the head of the HTML document in the style element. Inline styles Properties and values are added to an individual element with the style attribute. External Style Sheets The style rules are saved in a separate text-only .css file and attached via link or @import. Via link element in HTML: <head> <title>Titles are require</title> <link rel="stylesheet" href="/path/example.css"> </head> Via @import rule in a style sheet: <head> <title>Titles are required</title> <style> @import url("/path/example.css"); p {font-face: Verdana;} </style> </head> Embedded Style Sheets Embedded style sheets are placed in the head of the document via the style element: <head> <title>Titles are required</title> <style> /* style rules go here */ </style> </head> Inline Styles Apply a style declaration to a single element with the style attribute: <p style="font-size: large;">Paragraph text...</p> To add multiple properties, separate them with semicolons: <h3 style="color: red; margin-top: 30px;">Intro</h3> Document Structure Documents have an implicit structure. We give certain relationships names, as if they’re a family: • All the elements contained in a given element are its descendents. • An element that is directly contained within another element is the child of that element. • The containing element is the parent of the contained element. • Two elements with the same parent are siblings. Inheritance • Many properties applied to elements are passed down to the elements they contain. This is called inheritance. • For example, applying a sans-serif font to a p element causes the em element it contains to be sans-serif as well: Inheritance (cont’d) • Some properties inherit; others do not. Properties related to text usually inherit; properties related to layout generally don’t. • Styles explicitly applied to specific elements override inherited styles. • You’ll learn to use inheritance strategically to keep your style rules simple. The Cascade • The cascade refers to the system for resolving conflicts when several styles apply to the same element. • Style information is passed down (it “cascades” down) until overwritten by a style rule with more weight. • Weight is considered based on: • Priority of style rule source • Specificity of the selector • Rule order The Cascade: Priority Style rules from sources higher in this list override rules from sources listed below them. • Any style marked as !important by the user (to accommodate potential accessibility settings) • Any style marked !important by the author (of the web page) • Author styles (style sheets created in web site production) • User styles (added by the reader) • User agent styles (browser defaults) The Cascade: Specificity • When two rules in a single style sheet conflict, the type of selector is used to determine which rule has more weight. • For example, ID selectors are more specific than general element selectors. NOTE: Specificity will be discussed once we have covered more selector types. The Cascade: Rule Order • When two rules have equal weight, rule order is used. Whichever rule appears last “wins.” <style> p {color: red;} p {color: blue;} p {color: green;} </style> In this example, paragraphs would be green. • Styles may come in from external style sheets, embedded style rules, and inline styles. The style rule that gets parsed last (the one closest to the content) will apply. The Box Model Browsers see every element on the page as being contained in a little rectangular box. Block elements and inline elements participate in the box model. In this example, a blue border is added to all elements. The Box Model (cont’d) • The box model is the foundation of CSS page layout. • Apply properties such as borders, margins, padding, and backgrounds to element boxes. • Position, move, grow, and shrink boxes to create fixed or flexible page layouts. CSS Units of Measurement CSS provides a variety ways to specify measurements: Absolute units Have predefined meanings or real-world equivalents Relative units Based on the size of something else, such as the default text size or the size of the parent element Percentages Calculated relative to another value, such as the size of the parent element Absolute Units With the exception of pixels, absolute units are not appropriate for web design: px pixel in inches mm millimeters cm centimeters q 1/4 millimeter pt points (1/72 inch) pc pica (1 pica = 12 points = 1/6 inch) Relative Units Relative units are based on the size of something else: em a unit equal to the current font size ex x-height, equal to the height of a lowercase x rem root em, equal to the font size of the html element ch zero width, equal to the width of a zero (0) vw viewport width unit (equal to 1/100 of viewport width) vh viewport height unit (1/100 of viewport height) vmin viewport minimum unit (value of vh or vw, whichever is smaller) vmax viewport maximum unit (value of vh or vw, whichever is larger) RELATIVE UNITS The rem Unit • The rem (root em) unit is based on the font size of the html element, whatever that happens to be. • Default in modern browsers: Root font size is 16 pixels, so a rem = a 16-pixel unit. • If the root font size of the document changes, so does the size of a rem (and that’s good for keeping elements proportional). RELATIVE UNITS The em Unit • The em unit is traditionally based on the width of a capital letter M in the font. • When the font size is 16 pixels,1em = 16 pixels, 2em = 32 pixels, and so on. NOTE: Because they’re based on the font size of the current element, the size of an em may not be consistent across a page. RELATIVE UNITS Viewport Percentage Lengths (vw/vh) Viewport width (vw) and viewport height (vh) units are relative to the size of the viewport (browser window): vh = 1/100th width of viewport vh = 1/100th height of viewport They’re useful for making an element fill the viewport or a specified percentage of it. This image will be 50% the width and height of the viewport: img { width: 50vw; height: 50vh; } Browser Developer Tools Major browsers have built-in tools that aid development: • HTML, CSS, and JavaScript inspectors • Network speed reports • Animation tools • Other helpful features Browser Developer Tools (cont’d) Chrome DevTools (View > Developer > Developer Tools) Firefox, Safari, Opera, and Microsoft Edge also have developer tools. 12 FORMATTING TEXT OVERVIEW • Font-related properties • Text line settings • Various text effects • List style properties • ID, class, and descendent selectors • Specificity Designing Text Styling text on the web is tricky because you don’t have control over how the text displays for the user: • They may not have the font you specify. • They may have their text set larger or smaller than you designed it. Best practices allow for flexibility in text specification. Typesetting Terminology • A typeface is a set of characters with a single design (example: Garamond). • A font is a particular variation of the typeface with a specific weight, slant, or ornamentation (example: Garamond Bold Italic). • In traditional metal type, each size was a separate font (example: 12-point Garamond Bold Italic). • On a computer, fonts are generally stored in individual font files. CSS Basic Font Properties CSS font properties deal with specifying the shapes of the characters themselves: • font-family • font-size • font-weight • font-style • font-variant • font (a shorthand that includes settings for all of the above) Specifying the Font Family font-family Values: One or more font family names, separated by commas Example: body { font-family: Arial; } var { font-family: Courier, monospace; } Specifying the Font Family (cont’d) • Font names must be capitalized (except generic font families). • Use commas to separate multiple font names. • If the name has a character space, it must appear within quotation marks: p { font-family: "Duru Sans", Verdana, sans-serif; } Using Fonts on the Web • The font must be available on the user’s machine for it to display. • The best practice is to provide a list of options. The browser uses the first one that is available. • Start with the font you want and then provide backup options ending with a generic font family, as shown here: p { font-family: "Duru Sans", Verdana, sans-serif; } • You can also download a web font with the page, but it adds to the download and display time. Generic Font Families • Generic font families instruct the browser to use an available font from one of five stylistic categories: serif, sans-serif, monospace, cursive, fantasy • Generic font families are often used as the last backup option. Generic Font Families (cont’d) Specifying Font Size font-size Values: • CSS length units • Percentage value • Absolute keywords (xx-small, x-small, small, medium, large, x-large, xx-large) • Relative keywords (larger, smaller) Example: h1 { font-size: 2.5rem; } Specifying Font Size (cont’d) Most common sizing methods: • rem and em units • percentages (based on the inherited font size for that element) • pixels (px) can be used, but they’re not flexible. Font Size: rem Units • The rem (root em) is equal to the font size of the html (root) element. • In browsers, the default root size is 16 pixels, so: 1 rem = 16 pixels. • If the font size of the root is changed, rem measurements change too. • !!! Old browsers do not support rem units (IE8 and earlier). Font Size: em Units • The em unit is based on the current font size of the element. • The default font size is 16 pixels. By default, 1em = 16 pixels. • But if you change the font size of the element, the size of its em unit changes too. • Ems may be different sizes in different parts of the document and may compound larger or smaller when elements are nested. • This makes ems a little tricky to use, although they are better supported than rem units. Font Weight (Boldness) font-weight Values: normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900 Example: h1 { font-weight: normal; } span.new { font-weight: bold; } • Most common values are normal and . • Numerical values are useful when using a font with multiple weights. Font Style (Italics) font-style Values: normal, italic, oblique Example: cite { font-style: italic; } • Makes text italic, normal, or oblique (slanted, but generally the same as italics). Small Caps font-variant Values (in CSS2.1): normal, small-caps Example: abbr { font-variant: small-caps; } • Small caps are a separate font design that uses small uppercase characters in place of lowercase letters. • They help acronyms and other strings of capital letters blend in with the weight of the surrounding text. Condensed and Extended Text font-stretch Values (in CSS2.1): normal, ultra-condensed, extra-condensed, condensed, semicondensed, semi-expanded, expanded, extra-expanded, ultra-expanded Example: abbr { font-variant: small-caps; } Tells the browser to select a normal, condensed, or extended font variation from a typeface if it is available • The Shortcut font Property font Values (in CSS2.1): A list of values for all the individual properties, in this order: {font: style weight stretch variant size/line-height font-family} At minimum, it must contain font-size and font-family, in that order. Other values are optional and may appear in any order prior to font-size. Example: p { font: 1em sans-serif; } h3 { font: oblique bold small-caps 1.5em Verdana, sans-serif; } Advanced Typography The CSS3 Font Module offers properties for fine-tuned typography control, including: • Ligatures • Superscript and subscript • Alternate characters (such as a swash design for an S) • Proportional font sizing using x-height • Kerning • OpenType font features Text Line Treatments Some properties control whole lines of text: • Line height (line-height) • Indents (text-indent) • Horizontal alignment (text-align) Line Height line-height Values: Number, length, percentage, normal Example: p { line-height: 1.4em; } • Line height defines the minimum distance from baseline to baseline in text. Line Height (cont’d.) • The baseline is the imaginary line upon which the bottoms of characters sit. • If a large character or image is on a line, the line height expands to accommodate it. Indents text-indent Values: Length, percentage Examples: p {text-ident: 2em;} p {text-ident: 25%;} p {text-ident: -35px;} Horizontal Text Alignment text-align Values: left, right, center, justify, start, end Examples: Underlines (Text Decoration) text-decoration Values: none, underline, overline, line-through, blink Examples: NOTE: text-decoration is often used to turn off underlines under links: a { text-decoration: none; } Text Decoration Tips • If you turn off underlines under links, be sure there is another visual cue to compensate. • Underlining text that is not a link may be misleading. Consider italics instead. • Don’t use blink. Browsers don’t support it anyway. Capitalization text-transform Values: none, capitalize, lowercase, uppercase, full-width Examples: Spacing letter-spacing Values: length, normal word-spacing Values: length, normal Examples: Text Shadow text-shadow Values: 'horizontal-offset' 'vertical-offset' 'blur-radius' 'color', none The value is two offset measurements, an optional blur radius, and a color value (with no commas between). Example: List Style Properties There are three properties for affecting the display of lists: • list-style-type Chooses the type of list marker • list-style-position Sets the position of the marker relative to the list element box • list-style-image Allows you to specify your own image for use as a bullet LIST STYLES Choosing a Marker list-style-type Values: none, disc, circle, square, decimal, decimal-leading-zero, loweralpha, upper-alpha, lower-latin, upper-latin, lower-roman, upperroman, lower-greek Unordered lists: ul { list-style-type: keyword; } LIST STYLES Choosing a Marker (cont’d) Ordered lists: ol { list-style-type: keyword; } Keyword System decimal 1, 2, 3, 4, 5… decimal-leading-zero 01, 02, 03, 04, 05… lower-alpha a, b, c, d, e… upper-alpha A, B, C, D, E… lower-latin a, b, c, d, e… (same as lower-alpha) upper-latin A, B, C, D, E… (same as upper-alpha) lower-roman i, ii, iii, iv, v… upper-roman I, II, III, IV, V… lower-greek α, β, γ, δ, ε… LIST STYLES Marker Position list-style-position Values: inside, outside, hanging Positions the marker relative to the content area: LIST STYLES Custom Bullets list-style-image Values: url(location), none Example: ul { list-style-type: disc; list-style-image: url(/images/rainbow.gif); list-style-position: outside; } More Selector Types • Descendent selectors • ID selectors • Class selectors • Universal selector Descendent Selectors A descendent selector targets elements contained in another element. It’s a kind of contextual selector (it selects based on relationship to another element). It’s indicated in a list separated by a character space. ol a {font-weight: bold;} (only the links (a) in ordered lists (ol) would be bold) h1 em {color: red;} (only emphasized text in h1s would be red) Descendent Selectors (cont’d) They can appear as part of a grouped selector: h1 em, h2 em, h3 em {color: red;} (only emphasized text in h1, h2, and h3 elements) They can be several layers deep: ol a em {font-variant: small-caps;} (only emphasized text in links in ordered lists) ID Selectors ID selectors (indicated by a # symbol) target elements based on the value of their ID attributes: <li id="primary">Primary color t-shirt</li> To target just that item: li#primary {color: olive;} To omit the element name: #primary {color: olive;} It can be used as part of a compound or contextual selector: #intro a { text-decoration: none;} Class Selectors Class selectors (indicated by a . symbol) select elements based on the value of their class attributes: p.special { color: orange;} (All paragraphs with the class name "special" would be orange.) To target all element types that share a class name, omit the element name in the selector: .hilight { background-color: yellow;} (All elements with the class “hilight” would have a yellow background.) Universal Selector The universal element selector (*) matches any element, like a wildcard in programming languages: * {border: 1px solid gray;} (puts a 1-pixel gray border around every element in the document) Can be used as part of contextual selectors: #intro * {border: 1px solid gray;} (selects all elements contained within an element with the ID intro) Specificity Basics Specificity refers to a system for sorting out which selectors have more weight when resolving style rule conflicts. More specific selectors have more weight. In simplified terms, it works like this: • Inline styles with the style attribute are more specific than (and will override…) • ID selectors, which are more specific than (and will override…) • Class selectors, which are more specific than (and will override…) • Individual element selectors Calculating Specificity There is a system used to calculate specificity. Start by drawing three boxes: [ ] [ ] [ ] For each style rule: 1. Count the IDs in the selector and put that number in the first box. 2. Count the class and pseudo-class selectors and put the number in the second box. 3. Count the element names and put the number in the third box [ ID ] [ class ] [ elements ] 4. The first box that is not a tie determines which selector wins. Calculating Specificity (cont’d) Example: h1 { color: red;} [0] [0] [1] h1.special { color: lime; } [0] [1] [1] The second one has a class selector and the first one doesn’t, therefore the second one is more specific and has more weight. The lime color applies to h1s when they have the class name “special.” Using Specificity Use specificity strategically to take advantage of overrides: p { line-height: 1.2em; } [0] [0] [1] (sets the line-height for all paragraphs) blockquote p { line-height: 1em; } [0] [0] [2] (more specific selector changes line-height when the paragraph is in a blockquote) p.intro { line-height: 2em; } [0] [1] [1] (paragraphs with the class “intro” have a line-height of 2em, even when they’re in a blockquote. A class name in the selector has more weight than two element names.) 13 COLORS AND BACKGROUNDS OVERVIEW • CSS color names • RGB and HSL color values • Foreground and background colors • Tiling background images • More selectors and external style sheets Named Color Values Specify foreground or background color using one of 140 predefined CSS3 color names: h1 { color: red; } h2 { color: darkviolet; } body { background-color: papayawhip; } learningwebdesign.com/colornames.html Numeric Color Values For more control, define colors numerically using one of these color models: • RGB (combination of red, green, and blue light values) • RGBa (RGB plus alpha transparency) • HSL (hue, saturation, and luminosity) • HSLa (HSL plus alpha transparency) RGB Color The RGB color model mixes color with red, green, and blue light. Each channel can have 256 shades, for millions of color options. RGB Values in Style Rules There are four formats for providing RGB color values: • RGB values (0 to 255): rgb(200,178,230) • Percentage values: rgb(78%,70%,90%) • Hexadecimal values: #C8B2E6 • Condensed hexadecimal values (for double-digits only): #F06 is the same as #FF0066 Hexadecimal RGB Values Red, green, and blue values converted to hexadecimal and preceded by the # symbol. RGBa Color • RGB + an alpha channel for transparency • The first three values are RGB. The fourth is the transparency level from 0 (transparent) to 1 (opaque). HSL and HSLa • Colors described by values for hue (°), saturation (%), and luminosity (%): hsl(180,50%,75%) • Hue specifies the position on a color wheel (in degrees) that has red at 0°, green at 120°, and blue at 240°. • HSL is less commonly used than RGB, but some find it more intuitive. • HSLa adds an alpha value for transparency. Foreground Color color Values: Color value (named or numeric) Example: blockquote {border: 4px dashed; color: green;} The foreground of an element consists of its text and border (if one is specified). Background Color background-color Values: Color value (named or numeric) Example: blockquote {border: 4px dashed; background-color: green;} The background painting area of an element fills the area behind the text to the outer edge of the border. Clipping the Background background-clip Values: border-box, padding-box, content-box Specifies where the background painting area ends. Opacity opacity Values: number (0 to 1) Example: h1 {color: gold; background: white; opacity: .25;} Specifies the transparency level from 0 (transparent) to 1 (opaque): Tiling Background Images background-image Values: url(location of image), none Example: body {background-image: url(star.png);} Locates an image to be used as a tiling background image behind an element. By default, it starts at the top, left corner and repeats horizontally and vertically: Background Repeating background-repeat Values: repeat, no-repeat, repeat-x, repeat-y, space, round Specifies how the background image repeats and can restrict it to tiling in one direction or not at all: • repeat-x: Tiles horizontally only • repeat-y: Tiles vertically only • space: Adds space around images so they fit in the window with no clipping • round: Distorts the image so it fits without clipping Background Repeating (cont’d) Background Position background-position Values: Length, percentage, left, center, right, top, bottom Specifies the position of the origin image, the first image that is placed in the background from which tiling images extend. Examples (horizontal position goes first): background-position: left bottom; background-position: 300px 100px; background-position: 25% 100%; Background Position (cont’d) Background Attachment background-attachment Values: scroll, fixed, local Specifies whether the background image scrolls with the content or stays in a fixed position relative to the viewport. Background Size background-size Values: Length, percentage, auto, cover, contain Specifies the size of the tiling image: Shorthand background Property background Values: background-color background-image background-repeat background-attachment background-position background-clip background-origin background-size • Specifies all background properties in one declaration background: white url(star.png) no-repeat top center fixed; • Properties are optional and may appear in any order • Properties not represented reset to their defaults—be careful it doesn’t overwrite previous background settings. Multiple Background Images You can place more than one background image in a single image (separated by commas): body { background: url(image1.png) left top no-repeat, url(image2.png) center center no-repeat, url(image3.png) right bottom no-repeat; } Gradient Fills • A gradient is a transition from one color to another. • Linear gradients change colors along a line. • Radial gradients start at a point and spread outward in a circular or elliptical shape. • You can generate a gradient image for use as a background using linear-gradient() and radial-gradient() notation. Example: #banner { background-image: linear-gradient(180deg, aqua, green); } Linear Gradient The linear-gradient() notation provides the angle of a gradient line and the colors the line passes through. It is specified in degrees (deg) or keywords (to top, to right, to bottom, to left). Radial Gradients The radial-gradient() notation provides the color values and optional size, shape, and position information. Gradient Vendor Prefixes Because the gradient spec has changed over time, gradients require significant prefixing and alternate values: background: #ffff00; /* Old browsers */ background: -moz-linear-gradient(top, #ffff00 0%, #00ff00 100%); /* FF3.6+ */ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ffff00), colorstop(100%,#00ff00)); /* Chrome,Safari4+ */ background: -webkit-linear-gradient(top, #ffff00 0%,#00ff00 100%); /* Chrome10+,Safari5.1+ */ background: -o-linear-gradient(top, #ffff00 0%,#00ff00 100%); /* Opera 11.10+ */ background: -ms-linear-gradient(top, #ffff00 0%,#00ff00 100%); /* IE10+ */ background: linear-gradient(to bottom, #ffff00 0%,#00ff00 100%); /* W3C Standard */ filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffff00', endColorstr='#00ff00',GradientType=0 ); /* IE6-9 */ TIP: Use a tool like Ultimate CSS Gradient Generator: www.colorzilla.com/gradienteditor. Vendor Prefixes Browsers once kept experimental implementations of properties separate from the final release by adding a vendor prefix. Example: Property name: shape-outside Vendor-prefixed for Safari, Chrome, and Android: -webkit-shape-outside Vendor Prefixes (cont’d) Prefix Organization Most popular browsers -ms- Microsoft Internet Explorer -moz- Mozilla Foundation Firefox, Camino, SeaMonkey -o- Opera Software Opera, Opera Mini, Opera Mobile -webkit- Originally Apple; now open source Safari, Chrome, Android, Silk, BlackBerry, WebOS, and many others NOTE: Browser vendors no longer use the prefix system, but some properties from that era still require them. ShouldIPrefix.com is a good place to check for properties that still require prefixes. More Selector Types Pseudo-class selectors Pseudo-element selectors Attribute selectors Pseudo-Class Selectors Treat elements in a certain state as belonging to the same class :link Link Pseudo-classes Applies style to unvisited (unclicked) links :visited Applies style to visited links User Action Pseudo-classes :focus Applies when element is selected for input :hover Applies when the mouse pointer is over the element :active Applies when the element (such as a link or button) is in the process of being clicked or tapped Pseudo-classes (cont’d) Pseudo-classes must appear in the following order: a { text-decoration: none; } /* turns underlines off for all links */ a:link { color: maroon; } a:visited { color: gray; } a:focus { color: maroon; background-color: #ffd9d9; } a:hover { color: maroon; background-color: #ffd9d9; } a:active { color: red; background-color: #ffd9d9; } More Pseudo-Class Selectors Structural pseudo-classes Input pseudo-classes These allow selection based on where the element is in the structure of the document (the document tree): These selectors apply to states that are typical for form inputs: :enabled :root :disabled :empty :checked :first-child :last-child :only-child :first-of-type :last-of-type :only-of-type Location pseudo-classes (in addition to :link and :visited) :target (fragment identifier) Linguistic pseudo-class :lang() :nth-child() :nth-last-child() :nth-of-type() :nth-last-of-type() Logical pseudo-class :not() Pseudo-Element Selectors Applies styles to elements not explicitly marked up in the source. ::first-line Applies a style to the first line of an element: p:first-line {letter-spacing: 9px;} ::first-letter Applies a style to the first letter of an element: p:first-letter { font-size 300%; color: orange;} Pseudo-Element Selectors (cont’d.) The ::before and ::after pseudo-elements insert generated content before or after a specified element. ::before Inserts copy (provided with the content property) before an element and applies style properties to it as specified ::after Inserts copy (provided with the content property) after an element and applies style properties to it as specified Generated Content Example The style sheet: p.warning::before { content: url(exclamation.png); margin-right: 6px; } p.warning::after { content: " Thank you."; color: red; } The markup: <p class="warning">We are required to warn you that undercooked food is a health risk.</p> Attribute Selectors Targets elements based on attribute names or values. There are eight types: Simple attribute selector Matches an element with a given attribute: E[attribute] img[title] { border: 3px solid;} (Matches every img element that has a title attribute) Attribute Selectors (cont’d) Exact attribute value selector Matches an element with a specific value for an attribute: E[attribute="exact value"] img[title="first grade"] {border: 3px solid;} (matches only if the title value is "first grade") Partial attribute value selector (~) Matches an element by one part of an attribute value.: E[attribute~="value"] img[title~="grade"] {border: 3px solid;} (matches "first grade", "second grade", and so on) Attribute Selectors (cont’d.) Hyphen-separated attribute value selector (|) Targets hyphen-separated values: E[attribute|="value"] Beginning substring attribute value selector (^) Matches an element with attribute values that start with the given string of characters: E[attribute^="first part of a value"] Ending substring attribute value selector ($) Matches an element with attribute values that end with the given string of characters: E[attribute$="last part of a value"] Arbitrary substring attribute value selector (*) Looks for the text string in any part of the attribute value: E[attribute*="any part of the value"] External Style Sheets • Store styles in a separate .css file and attach to the document via <link> or @import • Most efficient method: Change styles in multiple documents by editing one .css file • A .css document is a simple text document (may begin with @charset to identify character set) Attaching a Style Sheet with the link Element • The link element defines a relationship between the current document and an external resource. • It goes in the head of the document. • Use the rel attribute to say it’s a style sheet. Use href to provide the URL of the .css file (relative to the current document): <head> <title>Titles are required.</title> <link rel="stylesheet" href="/path/stylesheet.css"> </head> Attaching a Style Sheet with an @import rule An @import rule imports the contents of an external style sheet into another style sheet (either a .css document or embedded with style): <head> <style> @import url("/path/stylesheet.css"); p { font-face: Verdana;} </style> <title>Titles are required.</title> </head> 14 THINKING INSIDE THE BOX OVERVIEW • • • • The parts of an element box • Outlines • Margins • Display roles • Drop shadows Box dimensions Padding Borders The Parts of an Element Box NOTE: The margin is indicated with a blue shade and outline, but is invisible in the layout. Specifying Box Dimensions width Values: Length, percentage, auto height Values: Length, percentage, auto Specify the dimensions of an element box with width and height properties Box Sizing Models box-sizing Values: content-box, border-box There are two methods for sizing an element box, specified with the box-sizing attribute: Content-box sizing (default) Applies width and height values to the content box only Border-box sizing Applies width and height values to the border box (including the padding and content) Box Sizing Models Compared Overflow overflow Values: visible, hidden, scroll, auto Specifies what to do when content doesn’t fit in a sized element box: Padding padding, padding-top, padding-right, padding-bottom, padding-left Values: Length, percentage An amount of space between the content area and the border (or the space the border would be if one isn’t specified). You can add padding to one side at a time, or on all sides with the padding shorthand property. Padding (cont’d) blockquote { padding-top: 2em; padding-right: 4em; padding-bottom: 2em; padding-left: 4em; background-color: #D098D4; /*light green*/ } Shorthand padding Property The padding property adds space around 1, 2, 3, or 4 sides of the content using the clockwise top, right, bottom, left (TRouBLe) order: padding: top right bottom left; padding: 2em 4em 2em 4em; (this shorthand produces the same result as the example on the previous slide) Shorthand padding Property (cont’d) If the left and right sides are the same, you can omit the last value, and the second value will be applied on both the left and right sides: padding: top right+left bottom; padding: 2em 4em 2em; (this shorthand produces the same result as the examples on the two previous slides) Shorthand padding Property (cont’d) If the top and and bottom sides are also the same, you can omit the third value, and the first value will be applied on both the top and bottom: padding: top+bottom right+left; padding: 2em 4em; (same result as previous examples) If all sides are the same, provide one value, and it’s applied to all sides: padding: all sides; padding: 2em; (2em padding all around) Borders • A border is a line drawn around the content area and its (optional) padding. • The thickness of the border is included in the dimensions of the element box. • You define style, width (thickness), and color for borders. • Borders can be applied to single sides or all around Border Style border-style, border-top-style, border-right-style, border-bottom-style, border-left-style Values: none, solid, hidden, dotted, dashed, double, groove, ridge, inset, outset NOTE: The default is none, so if you don’t define a border style, it won’t appear. Border Style border-style The border-style shorthand uses the clockwise (TRouBLe) shorthand order. The following rules have the same effect: div#silly { border-top-style: solid; border-right-style: dashed; border-bottom-style: double; border-left-style: dotted; width: 300px; height: 100px; } div#silly { border-style: solid dashed double dotted; } Border Width border-width, border-top-width, border-right-width, border-bottom-width, border-left-width Values: Length, thin, medium, thick The border-width shorthand uses the clockwise (TRouBLe) order: div#help { border-width: thin medium thick 12px; border-style: solid; width: 300px; height: 100px; } NOTE: The border-style property is required for the border to be rendered. Border Color border-color, border-top-color, border-right-color, border-bottom-color, border-left-color Values: Color value (named or numeric) The border-color properties override the color property: div#special { border-color: maroon aqua; border-style: solid; border-width: 6px; width: 300px; height: 100px; } NOTE: The border-style property is required for the border to be rendered. Border Shorthand Properties border, border-top, border-right, border-bottom, border-left Values: border-style border-width border-color Combine style, width, and color values in shorthand properties for each side or all around (border): p.example { border: 2px dotted aqua; } NOTE: The border-style property must be included in the shorthand for the border to be rendered. Border Radius (Rounded Corners) border-radius Values: 1, 2, 3, or 4 length or percentage values • The border-radius property rounds off the corners of an element. • The value is a length or percentage value reflecting the radius of the curve. • Providing one value makes all the corners the same. • Four values are applied clockwise, starting from the top-left corner. Border Radius (cont’d) Margins margin, margin-top, margin-right, margin-bottom, margin-left Values: Length, percentage The margin is an amount of space added on the outside of the border. They keep elements from bumping into one another or the edge of the viewport. The shorthand margin property works the same as the padding shorthand. Values are applied clockwise (TRouBLe order) and are repeated if fewer than 4 values are supplied. Margins (cont’d) A p#A { margin: 4em; border: 2px solid red; background: #e2f3f5; } B p#B { margin-top: 2em; margin-right: 250px; margin-bottom: 1em; margin-left: 4em; border: 2px solid red; background: #e2f3f5; } C body { margin: 0 20%; border: 3px solid red; background-color: #e2f3f5; } Margins (cont’d) Top and bottom margins of neighboring elements collapse (they overlap instead of accumulating). The top element has a bottom margin of 4em. The bottom element has a top margin of 2em. The resulting margin is 4em (the largest value). Assigning Display Types display Values: inline | block | run-in | flex | grid | flow | flow-root | list-item | table | table-row-group | table-header-group | table-footer-group | table-row | table-cell | table-column-group | table-column | table-caption | ruby | ruby-base | ruby-text | ruby-base-container | ruby-text-container | inline-block | inline-table | inline-flex | inline-grid | contents | none Assigns a display type that determines how the element box behaves in layouts. Examples: • Make li (normally block elements) into inline elements so they line up in a horizontal menu: nav li { display: inline; } • Make an anchor (a) element (normally inline) display as a block so you can give it a width and height: nav li a { display: block; } Box Drop Shadows box-shadow Values: horizontal-offset vertical-offset blur-distance spreaddistance color inset, none Applies a drop shadow around the visible element box. The values are a horizontal and vertical offset, optional blur and spread values (in pixels), a color value, and the option to make it appear inset. Box Drop Shadows (cont’d) A box-shadow: 6px 6px gray; B box-shadow: 6px 6px 5px gray; /* 5 pixel blur */ C box-shadow: 6px 6px 5px 10px gray; /* 5px blur,10px spread */ 15 FLOATING AND POSITIONING OVERVIEW • Understanding normal flow • Floating elements to the left and right • Clearing and containing floated elements • Text wrap shapes • Positioning: Absolute, relative, fixed Normal Flow In the normal flow, elements are laid out from top to bottom in the order in which they appear in the source and from left to right (in left-to-right reading languages). Floating float Values: left, right, none Moves an element as far as possible to the left or right and allows the following content to wrap around it: img { float: right; } Floating (cont’d) • Floated elements are removed from the normal flow but influence the surrounding content. • Floated elements stay within the content area of the element that contains it. • Margins are always maintained (they don’t collapse) on all sides of floated elements. • You must provide a width for a floated text element (because default width is auto). • Elements don’t float higher than their reference in the source. Clearing Floated Elements clear Values: left, right, both, none Prevents an element from appearing next to a floated element and forces it to start against the next available “clear” space img { float: left; margin-right: .5em; } h2 { clear: left; margin-top: 2em; } (The h2 is “cleared” and starts below the floated element.) Floating Multiple Elements • When you float multiple elements, browsers follow rules in the spec to ensure they don’t overlap. • Floated elements will be placed as far left or right (as specified) and as high up as space allows. CSS Shapes (Text Wrap) shape-outside Values: none, circle(), ellipse(), polygon(), url(), [margin-box | padding-box | content-box ] Changes the shape of the text wrap to a circle or ellipse, a complex path, or based on transparent areas in an image shape-margin Values: length, percentage Specifies an amount of space to hold between the image and the wrapped text CSS Shapes (cont’d) Positioning position Values: static, relative, absolute, fixed, sticky Indicates that an element is to be positioned and specifies which positioning method to use top, right, bottom, left Values: length, percentage, auto Offset properties that provide the distance the element should be moved away from that respective edge Types of Positioning • Static: The default position in the flow • Relative: Moves the element relative to its original position • Absolute: Removes the element from the flow and places it relative to the viewport or other containing element • Fixed: Element stays in one position relative to the viewport • Sticky: Element starts in the flow but stays fixed once it scrolls to a particular position relative to the viewport Relative Positioning • Moves the element relative to its original position • The space it originally occupied is preserved. em { position: relative; top: 2em; /* moves it down */ left: 3em; /* moves it right */ background-color: fuchsia; } Absolute Positioning • Moves the element relative to the viewport or containing block element • The space it originally occupied is closed up. em { position: absolute; top: 2em; left: 3em; background-color: fuchsia; } Containing Blocks • A positioned element serves as a containing block (or positioning context) for the elements it contains. • If a positioned element has an ancestor that has its position set to relative, absolute, or fixed, then its position will be relative to that containing block element. • If a positioned element is not contained within another positioned element, then it is placed relative to the initial containing block (the html element) and the viewport. Containing Blocks (cont’d.) p { position: relative; padding: 15px; background-color: #F2F5D5; border: 2px solid purple; } em { position: absolute; top: 2em; left: 3em; background-color: fuchsia; } The relatively positioned p element acts as a containing block for the em element. Specifying Position • Position can be specified in length measurements (like pixels) or percentages. • The measurement moves it away from the positioning offset property provided (i.e., top: 200px; moves the element DOWN from the top edge). • Be careful not to overspecify. Two offset properties are usually enough. Stacking Order z-index Values: Number, auto 16A CSS LAYOUT WITH FLEXBOX OVERVIEW • Flexbox terminology • Flexbox containers • Flow: Flow direction and text wrap • Alignment on main and cross axes • Specifying how items in a flexbox "flex" • Changing the order of flex items About Flexbox • Flexbox is a display mode that lays out elements along one axis (horizontal or vertical). • Useful for menu options, galleries, product listings, etc. • Items in a flexbox can expand, shrink, and/or wrap onto multiple lines, making it a great tool for responsive layouts. • Items can be reordered, so they aren't tied to the source order. • Flexbox can be used for individual components on a page or the whole page layout. Flexbox Container display: flex • To turn on Flexbox mode, set the element’s display to flex. • This makes the element a flexbox container. • All of its direct children become flex items in that container. • By default, items line up in the writing direction of the document (left to right rows in left-to-right reading languages). Flexbox Container (cont’d) Rows and Columns (Direction) flex-direction Values: row, column, row-reverse, column-reverse The default value is row (for L-to-R languages), but you can change the direction so items flow in columns or in reverse order: Wrapping Flex Lines flex-wrap Values: wrap, nowrap, wrap-reverse Flex items line up on one axis, but you can allow that axis to wrap onto multiple lines with the flex-wrap property: Flex Flow (Direction + Wrap) flex-flow Values: Flex-direction flex-flow The shorthand flex-flow property specifies both direction and wrap in one declaration. Example #container { display: flex; height: 350px; flex-flow: column wrap; } Flexbox Alignment Terminology • Flexbox is “direction-agnostic,” so we talk in terms of main axis and cross axis instead of rows and columns. • The main axis runs in whatever direction the flow has been set. • The cross axis runs perpendicular to the main axis. • Both axes have a start, end, and size. ROW: Main and Cross Axes COLUMN: Main and Cross Axes Aligning on the Main Axis justify-content Values: flex-start, flex-end, center, space-between, space-around When there is space left over on the main axis, you can specify how the items align with the justify-content property (notice we say start and end instead of left/right or top/bottom). The justify-content property applies to the flex container. Example: #container { display: flex; justify-content: flex-start; } Aligning on the Main Axis (cont’d) When the direction is row, and the main axis is horizontal Aligning on the Main Axis (cont’d.) When the direction is column, and the main axis is vertical NOTE: I needed to specify a height on the container to create extra space on the main axis. By default, it’s just high enough to contain the content. A WORD FROM THE AUTHOR “Keeping the main and cross axes straight in your mind when changing between rows and columns is one of the trickiest parts of using Flexbox. Once you master that, you’ve got it!” —Jennifer Robbins Aligning on the Cross Axis align-items Values: flex-start, flex-end, center, baseline, stretch When there is space left over on the cross axis, you can specify how the items align with the align-items property. The align-items property applies to the flex container. Example: #container { display: flex; flex-direction: row; height: 200px; align-items: flex-start; } Aligning on the Cross Axis (cont’d) When the direction is row, the main axis is horizontal, and the cross axis is vertical. NOTE: I needed to specify a height on the container to create extra space on the cross axis. By default, it’s just high enough to contain the content. Aligning on the CROSS Axis (cont’d) align-self Values: flex-start, flex-end, center, baseline, stretch Aligns an individual item on the cross axis. This is useful if one or more items should override the align-items setting for the container. The align-self property applies to the flex item. Example: .box4 { align-self: flex-end; } Aligning on the CROSS Axis (cont’d) align-content Values: flex-start, flex-end, center, space-around, space-between, stretch When lines are set to wrap and there is extra space on the cross axis, use align-content to align the lines of content. The align-content property applies to the flex container. Aligning with Margins Use a margin (set to auto) to put extra space on the side of particular flex items. Example: Adding an auto margin to the right of the first flex item (the li with the logo) pushes the remaining li to the right: ul { display: flex; align-items: center; ... } li.logo { margin-right: auto; } Specifying How Items “Flex” flex Values: none, 'flex-grow flex-shrink flex-basis' • Items can resize (flex) to fill the available space on the main axis in the container. • The flex property identifies how much an item can grow and shrink and identifies a starting size • It distributes extra space in the container within items (compared to justify-content that distributes space between and around items). flex Property Example flex is a shorthand for separate flex-grow, flex-shrink, and flex-basis properties. The values 1 and 0 work like on/off switches. li { flex: 1 0 200px; } In this example, list items in the flex container start at 200 pixels wide, are permitted to expand wider (flex-grow: 1), and are not permitted to shrink (flex-shrink: 0). NOTE: The spec recommends always using the flex property and using individual properties only for overrides. Expanding Items (flex-grow) flex-grow Values: Number Specifies whether and in what proportion an item may stretch larger. 1 allows expansion; 0 prevents it. flex-grow is applied to the flex item element. Expanding Items (cont’d) Relative Flex When the flex-basis has a value other than 0, higher integer values act as a ratio that applies more space within that item. Example: A value of 3 assigns three times more space to box4 than items with a flex-grow value of 1. (Note that it isn't necessarily 3x as wide as the other items.) .box4 { flex: 3 1 auto; } Expanding Items (cont’d.) Absolute Flex When the flex-basis is 0, items get sized proportionally according to the flex ratio. Example: A value of 3 makes “box4” 3x as wide as the others when flex-basis: 0. .box4 { flex: 3 1 0%; } Shortcut flex Values • flex: initial (same as flex: 0 1 auto;) Prevents the item from growing, but allows it to shrink to fit the container • flex: auto (same as flex: 1 1 auto;) Allows items to be fully flexible as needed. Size is based on the width/height properties. • flex: none (same as flex: 0 0 auto;) Creates a completely inflexible item while sizing it to the width/height properties. • flex: integer (same as flex: integer 1 0px;) Creates a flexible item with absolute flex (so flex-grow integer values are applied proportionally) Changing Item Order order Values: Number Specifies the order in which a particular item should appear in the flow (independent of the HTML source order): • order is applied to the flex item element. • The default is 0. Items with the same order value are placed according to their order in the source. • Items with different order values are arranged from lowest to highest. • The specific number value doesn’t matter; only how it relates to other values (like z-index) matters. Changing Item Order (cont’d) Example: “box3” has a higher order value (1) than the others with default order of 0. It appears last in the line even though it’s third in the markup: .box3 { order: 1; } Changing Item Order (cont’d) Ordinal groups Items that share the same order value are called an ordinal group. Ordinal groups stick together and are arranged from lowest value to highest: .box2, .box3 { order: 1; } Browser Support for Flexbox The Flexbox spec changed over the years and was implemented by browsers along the way: • Current version (2012): display: flex; Supported by all current desktop and mobile browser versions • “Tweener” version (2011): Supported by IE10 only • Old version (2009): display: box; Supported by Chrome <21, Safari 3.1–6, Firefox 2–21; iOS 3.2– 6.1, Android 2.1–4.3 display: flexbox; Browser Support (cont’d) To ensure that Flexbox works across all supporting browsers, you need a lot of vendor prefixes and redundant declarations. Use a tool like Autoprefixer to generate all that code for you (autoprefixer.github.io). Flexbox Property Review Flex container properties Flex item properties display align-self flex-flow flex flex-direction flex-grow flex-wrap flex-shrink justify-content align-items align-content flex-basis order 16B CSS LAYOUT WITH GRID OVERVIEW • Grid terminology • Grid display type • Creating the grid template • Naming grid areas • Placing grid items • Implicit grid behavior • Grid spacing and alignment How CSS Grids Work 1. Set an element’s display to grid to establish a grid container. Its children become grid items. 2. Set up the columns and rows for the grid (explicitly or with rules for how they are created on the fly). 3. Assign each grid item to an area on the grid (or let them flow in automatically in sequential order). Grid Terminology Creating a Grid Container To make an element a grid container, set its display property to grid. All of its children automatically become grid items. The markup <div id="layout"> <div id="one">One</div> <div id="two">Two</div> <div id="three">Three</div> <div id="four">Four</div> <div id="five">Five</div> </div> The styles #layout { display: grid; } Defining Row and Column Tracks grid-template-rows grid-template-columns Values: none, list of track sizes and optional line names • The value of grid-tempate-rows is a list of the heights of each row track in the grid. • The value of grid-template-columns is a list of the widths of each column track in the grid. #layout { display: grid; grid-template-rows: 100px 400px 100px; grid-template-columns: 200px 500px 200px; } • The number of sizes provided determines the number of rows/columns in the grid. This grid in the example above has 3 rows and 3 columns. Grid Line Numbers Browsers assign a number to every grid line automatically, starting with 1 from the beginning of each row and column track and also starting with –1 from the end. Grid Line Names You can also assign names to lines to make them more intuitive to reference later. Grid line names are added in square brackets in the position they appear relative to the tracks. To give a line more than one name, include all the names in brackets, separated by spaces. #layout { display: grid; grid-template-rows: [header-start] 100px [header-end content-start] 400px [content-end footer-start] 100px; grid-template-columns: [ads] 200px [main] 500px [links] 200px; } Track Size Values The CSS Grid spec provides a lot of ways to specify the width and height of a track. Some of these ways allow tracks to adapt to available space and/or to the content they contain: • Lengths (such as px or em) • Percentage values (%) • Fractional units (fr) • minmax() • min-content, max-content • auto • fit-content() Fractional Units (fr) The Grid-specific fractional unit (fr) expands and contracts based on available space: #layout { display: grid; grid-template-rows: 100px 400px 100px; grid-template-columns: 200px 1fr 200px; } Size Range with minmax() • The minmax() function constricts the size range for the track by setting a minimum and maximum dimension. • It’s used in place of a specific track size. • This rule sets the middle column to at least 15em but never more than 45em: grid-template-columns: 200px minmax(15em, 45em) 200px; min-content and max-content min-content is the smallest that a track can be. max-content allots the maximum amount of space needed. auto lets the browser take care of it. Start with auto for contentbased sizing. Repeating Track Sizes The shortcut repeat() function lets you repeat patterns in track sizes: repeat(#, track pattern) The first number is the number of repetitions. The track sizes after the comma provide the pattern: BEFORE: grid-template-columns: 200px 20px 1fr 20px 1fr 20px 1fr 20px 1fr 20px 1fr 20px 1fr 200px; AFTER: grid-template-columns: 200px repeat(5, 20px 1fr) 200px; (Here repeat() is used in a longer sequence of track sizes. It repeats the track sizes 20px 1fr 5 times.) Repeating Track Sizes (cont’d.) You can let the browser figure out how many times a repeated pattern will fit with auto-fill and auto-fit values instead of a number: grid-template-rows: repeat(auto-fill, 15em); auto-fill creates as many tracks as will fit in the available space, even if there’s not enough content to fill all the tracks. auto-fit creates as many tracks as will fit, dropping empty tracks from the layout. NOTE: If there’s leftover space in the container, it’s distributed according to the provided vertical and horizontal alignment values. Giving Names to Grid Areas grid-template-areas Values: none, series of area names by row • grid-template-areas lets you assign names to areas in the grid to make it easier to place items in that area later. • The value is a list of names for every cell in the grid, listed by row. • When neighboring cells share a name, they form a grid area with that name. Giving Names to Grid Areas (cont’d) #layout { display: grid; grid-template-rows: [header-start] 100px [content-start] 400px [footer-start] 100px; grid-template-columns: [ads] 200px [main] 1fr [links] 200px; grid-template-areas: "header header header" "ads main links" "footer footer footer" } Giving Names to Grid Areas (cont’d) Assigning names to lines with -start and -end suffixes creates an area name implicitly. Similarly, when you specify an area name with grid-template-areas, line names with -start and -end suffixes are implicitly generated. The grid Shorthand Property grid Values: none, row info/column info The grid shorthand sets values for grid-template-rows, grid-template-columns, and grid-template-areas. NOTE: The grid shorthand is available, but the word on the street is that it’s more difficult to use than separate template properties. The grid Shorthand Property (cont’d) Put the row-related values before the slash (/) and column-related values after: grid: rows / columns Example: #layout { display: grid; grid: 100px 400px 100px / 200px 1fr 200px; } The grid Shorthand Property (cont’d) You can include line names and area names as well, in this order: [start line name] "area names" <track size> [end line name] Example: #layout { display: grid; grid: [header-start] "header [content-start] "ads [footer-start] "footer / [ads] 200px [main] 1fr } header main footer [links] header" 100px links" 400px footer" 100px 200px; The names and height for each row are stacked here for clarity. Note that the column track information is still after the slash (/). Placing Items Using Grid Lines grid-row-start grid-row-end grid-column-start grid-column-end Values: auto, "line name", span number, span "line name", number "line name" • These properties position grid items on the grid by referencing the grid lines where they begin and end. • The property is applied to the grid item element. Placing Items on the Grid (cont’d) By line number: #one { grid-row-start: 1; grid-row-end: 2; grid-column-start: 1; grid-column-end: 4; } Using a span: #one { ... grid-column-start: 1; grid-column-end: span 3; } Starting from the last grid line and spanning backward: #one { ... grid-column-start: span 3; grid-column-end: -1; } By line name: #one { grid-row-start: header-start; grid-row-end: header-end; … } Placing Items on the Grid (cont’d) grid-row grid-column Values: "start line” / “end line” These shorthand properties combine the *-start and *-end properties into a single declaration. Values are separated by a slash (/): #one { grid-row: 1 / 2; grid-column: 1 / span 3; } Placing Items on the Grid Using Areas grid-area Values: Area name, 1 to 4 line identifiers Positions an item in an area created with grid-template-areas: #one { grid-area: header; } #two { grid-area: ads; } #three { grid-area: main; } #four { grid-area: links; } #five { grid-area: footer; } Implicit Grid Behavior The Grid Layout system does some things for you automatically (implicit behavior): • Generating “-start” and “-end” line names when you name an area (and vice versa) • Flowing items into grid cells sequentially if you don’t explicitly place them • Adding rows and columns on the fly as needed to fit items Automatically Generated Tracks grid-auto-rows grid-auto-columns Values: List of track sizes Provide one or more track sizes for automated tracks. If you provide more than one value, it acts as a repeating pattern. Example: Column widths are set explicitly with a template, but columns will be generated automatically with a height of 200 pixels: grid-template-columns: repeat(3, 1fr); grid-auto-rows: 200px; Flow Direction and Density grid-auto-flow Values: row or column, dense (optional) Specifies whether you’d like items to flow in by row or column. The default is the writing direction of the document. Example: #listings { display: grid; grid-auto-flow: column dense; } Flow Direction and Density (cont’d) The dense keyword instructs the browser to fill in the grid as densely as possible, allowing items to appear out of order. The Grid Property (Revisited) Use the auto-flow keyword in the shorthand grid property to indicate that the rows or columns should be generated automatically. Example: Columns are established explicitly, but the rows generate automatically. (Remember, row information goes before the slash.) grid: auto-flow 200px / repeat(3, 1fr); Because auto-flow is included with row information, grid-autoflow is set to row. Spacing Between Tracks grid-row-gap grid-column-gap Values: Length (must not be negative) grid-gap Values: grid-row-gap grid-column-gap Adds space between the row and/or columns tracks of the grid NOTE: These property names will be changing to row-gap, columngap, and gap, but the new names are not yet supported. Space Between Tracks (cont’d) If you want equal space between all tracks in a grid, use a gap instead of creating additional spacing tracks: grid-gap: 20px 50px; (Adds 20px space between rows and 50px between columns) Item Alignment justify-self align-self Values: start, end, center, left, right, self-start, self-end, stretch, normal, auto When an item element doesn’t fill its grid cell, you can specify how it should be aligned within the cell. justify-self aligns on the inline axis (horizontal for L-to-R languages). align-self aligns on the block (vertical) axis. Item Alignment (cont’d) NOTE: These properties are applied to the individual grid item element. Aligning All the Items justify-items align-items Values: start, end, center, left, right, self-start, self-end, stretch, normal, auto These properties align items in their cells all at once. They are applied to the grid container. justify-items aligns on the inline axis. align-items aligns on the block (vertical) axis. Track Alignment justify-content align-content Values: start, end, center, left, right, stretch, space-around, space-between, space-evenly When the grid tracks do not fill the entire container, you can specify how tracks align. justify-content aligns on the inline axis (horizontal for L-to-R languages). align-content aligns on the block (vertical) axis. Track Alignment (cont’d) NOTE: These properties are applied to the grid container. Grid Property Review Grid item properties Grid container properties display: grid | inline-grid grid grid-template grid-template-rows grid-template-columns grid-template-areas grid-auto-rows grid-auto-columns grid-auto-flow grid-gap grid-row-gap grid-column-gap justify-items align-items justify-content align-content grid-column grid-column-start grid-column-end grid-row grid-row-start grid-row-end grid-area justify-self align-self order (not part of Grid Module) z-index (not part of Grid Module) 17 RESPONSIVE WEB DESIGN OVERVIEW • What RWD is • Fluid layouts • Media queries • Design strategies and patterns • Testing options Introduction to RWD • RWD is a design and production approach that allows a web page to adapt to the screen it is viewed on. • The same HTML source is styled differently based on the width of the screen. • It ensures mobile users get the same content as other users, with a presentation that optimizes usability. • The term was coined by Ethan Marcotte in 2010 in his article “Responsive Web Design” for A List Apart. Introduction to RWD (cont’d) The Components of RWD Ethan Marcotte defines the three core components as follows: • A flexible grid Elements are sized so they squeeze and flow into the available browser space. • Flexible images Images and other embedded media scale to fit their containing elements. • CSS media queries These are a way to test for browser features such as viewport width and deliver styles accordingly. Setting the Viewport • Mobile browsers render pages on a canvas called the viewport and then shrink it to fit the screen (device width). • For example, a web page be rendered on a 980-pixel viewport and shrunk down to fit a 480-pixel wide screen. • To make the viewport the same size as the device width: <meta name="viewport" content="width=device-width, initial-scale="1"> Setting the Viewport (cont’d) Flexible Grids (Fluid Layout) Flexible Grid (Fluid Layout ) • Fluid layouts are the best approach for designing for a wide range of screen widths • For flexibility, use: • fr and minmax() and content-based grid track values • flex in Flexbox • percentage measurements Making Images Flexible To make images scale down to fit the size of their container: img { max-width: 100%; } Media Queries A media query is a special rule that tests for certain conditions before applying the styles it contains: @media type and (feature: value) { /* styles for browsers that meet this criteria */ } A few query examples: • Is it on a screen or printed? • Is the browser at least a certain width? • Is the orientation landscape or portrait? Media Query Example @media screen and (orientation: landscape) { body { background: skyblue; } } @media screen and (orientation: portrait) { body { background: coral; } } Media Types • The first part of a media query identifies the media type. • The current media types are all, print, screen, and speech. Example: @media print { /* print-specific styles between the brackets */ } • Media types were introduced in CSS2. Media Feature Queries CSS3 introduced media feature queries that test for a particular feature of a viewport or device. Example: h1 headings display in Lobster font only when the viewport is at least 40em wide. h1 { font-family: Georgia, serif; } @media screen and (min-width: 40em) { h1 { font-family: 'Lobster', cursive; } } NOTE: min-width and max-width queries are most useful for RWD. Using Media Queries In a style sheet: • Put an @media rule in a style sheet to deliver styles based on viewport width. • Make sure the @media rule comes after your baseline styles. With external style sheets: • Link or @import separate style sheets based on a query: <link rel="stylesheet" href="styles.css"> <link rel="stylesheet" href="2column-styles.css" media="screen and (min-width:1024px)"> Breakpoints • A breakpoint is the point at which we use a media query to introduce a style change. • Best practice is to create breakpoints for individual parts of the page rather than the entire page at once. • Designers generally create the narrow-screen version first and then change components as needed as the screen grows larger. • Em-based breakpoints introduce layout changes proportional to font size. Breakpoints (cont’d.) A few breakpoints used by Etsy.com (2018) Designing Responsively You need to pay attention to the following aspects of the page in a responsive design: • Content hierarchy • Layout • Typography • Navigation • Images • Special content like tables and forms Content Hierarchy • The biggest challenge is deciding what is visible in the first screen on small devices. • You should strive for content parity across devices. Everyone should have access to the same information, even if it’s not in exactly the same place. • Content organization is the most important part of site planning. It’s often handled by information architects or content strategists. Layout • RWD is based on fluid layouts. • The most common approach is to start with one column on small devices and add columns as space is available. • The optimum width of a text element should be based on a line length of 45 to 75 characters. If lines are much longer, introduce a breakpoint. Responsive Layout Patterns Typography • Typography should be optimized for different screen sizes. • Avoid complicated font styles on small screens. • Set font size to keep line lengths between 45 to 75 characters. • Line height should generally be larger on larger screens. • Left and right margins can increase on larger screens. Navigation Options Navigation Options (cont’d) Images • Use responsive image markup techniques. • Serve the smallest file size version by default. • Make sure important image detail isn’t lost at smaller sizes. Allow zooming or provide a cropped version. • Avoid text in graphics or provide alternative versions with larger type for small screens. Special Content • Forms Design for efficiency and flexibility (Flexbox) • Tables Research responsive table patterns • Interactive elements — Scale videos proportionally. — Explore alternatives that work better on small screens (for example, linking to a map app instead of just providing a small embedded map). Site Testing Testing sites in a wide variety of browsing environments is critical: • Real devices The best way to test is on actual smartphones, tablets, etc. • Emulators Use a desktop application that simulates device hardware and software. • Browser testing services Subscription-based services show how your site looks on a huge variety of browsers. 18 TRANSITIONS, TRANSFORMS, AND ANIMATION OVERVIEW • Creating smooth transitions • Moving, rotating, and scaling elements • Combining transitions and transforms • 3-D transforms • Keyframe animation overview CSS Transitions • CSS transitions create a smooth change from one state to another. • They fill in the frames in between (tweening). • Example: Gradually changing a button from red to blue (through purple) when the mouse pointer hovers over it. State 1: Default State 2: When the mouse is over the element Transition Properties transition-property Which CSS property to change transition-duration How long the transition should take in seconds (or milliseconds) transition-timing-function The manner in which the transition accelerates transition-delay Whether there should be a pause before the transition starts and how long that pause should be (in seconds) Specifying the Property transition-property Values: Property-name, all, none Identifies the property that will receive a transition when it changes state. Here, we want to smooth out the change in background color when the color changes from hovering or focus: .smooth { ... color: #fff; background-color: mediumblue; transition-property: background-color; } .smooth:hover, .smooth:focus { background-color: red; } Defining Duration transition-duration Values: Time Identifies how much time the transition will take. It’s usually specified in seconds (s) or milliseconds (ms). In this example, the transition from blue to red takes .3 seconds: .smooth { ... color: #fff; background-color: mediumblue; transition-property: background-color; transition-duration: .3s; } .smooth:hover, .smooth:focus { background-color: red; } Timing Functions transition-timing-function Values: ease, linear, ease-in, ease-out, ease-in-out, step-start, step-end, steps, cubic-bezier(#,#,#,#) • The timing function describes the way the transition accelerates or decelerates over time. • It has a big impact on the feel and believability of the animation. • The default is ease, which starts slowly, accelerates quickly, then slows down again at the end. Timing Functions (cont’d) • linear: Stays consistent from beginning to end, feels mechanical • ease-in: Starts slowly, then speeds up • ease-out: Starts quickly, then slows down • ease-in-out: Similar to ease, but with less acceleration in the middle • cubic-bezier(#,#,#,#): Defines a curve that plots acceleration • steps(#, start or end): Divides the animation into a number of steps. The start and end keywords indicate whether that transition happens at the beginning or end of each step. • step-start: Changes states in one step, at the beginning of the duration time • step-end: Changes states in one step, at the end of the duration time Cubic Bezier Curves • Acceleration can be plotted using a Bezier curve. • Steep sections indicate quick rate of change; flat parts indicate slow rate of change. • The curve is defined by the x,y coordinates of “handles” that control the curve. Cubic Bezier Curves for Keywords The curves for transition-timing-function keyword values: Transition Delay transition-delay Values: Time Delays the start of the transition by the amount of time specified. In this example, the transition will begin .2 seconds after the user hovers over the element: .smooth { ... color: #fff; background-color: mediumblue; transition-property: background-color; transition-duration: .3s; transition-timing-function: ease-in-out; transition-delay: 0.2s; } .smooth:hover, .smooth:focus { background-color: red; } Shorthand transition Property transition Values: property duration timing-function delay Combines all the transition properties into one declaration. Values are separated by character spaces. The duration time must appear before delay time. .smooth { ... color: #fff; background-color: mediumblue; transition: background-color .3s ease-in-out 0.2s; } Transitioning Multiple Properties • You can set the transitions for multiple properties with one declaration. • Separate value sets with commas. • This declaration smoothes out the changes in background color, color, and letter spacing of an element: .smooth { … transition: background-color 0.3s ease-out 0.2s, color 2s ease-in, letter-spacing 0.3s ease-out; } Making All Transitions Smooth If you want the same duration, timing-function, and delay for all your transitions, use the all keyword for transitionproperty: .smooth { … transition: all 0.2s ease-in-out; } CSS Transforms transform Values: rotate(), rotateX(), rotateY(), translate(), translateX(), translateY(), scale(), scaleX(), scaleY(), skew(), skewX(), skewY(), none The transform property changes the shape and location of an element when it initially renders. It is not animated but can be with transitions. Transforming the Angle (rotate) Use the rotate() function as the value of transform to rotate the element at a given angle: img { width: 400px; height: 300px; transform: rotate(-10deg); } Transform Origin transform-origin Values: Percentage, length, left, center, right, top, bottom The point around which an element is transformed, defined by horizontal and vertical offsets. Transforming Position (translate) • Use the translate() function as the value of transform to render an element at a new location. • The values are an x-offset and a y-offset. When you provide one value, it’s used for both axes. Transforming Size (scale) • Use the scaleX(), scaleY(), or scale function to change the size at which an element renders. • The value is a unitless number that specifies a size ratio. • The scale() shorthand provides x-offset and y-offset values (providing one value applies to both axes). Transforming Slant (skew) • Use the skewX(), skewY(), or skew function to change the angle of the horizontal or vertical axes (or both). • The value is the number of degrees the angle should be. • The skew() shorthand provides x-offset and y-offset values (providing one value applies it to the x-axis only). Multiple Transforms You can apply more than one transform type in a declaration: img:hover, img:focus { transform: scale(1.5) rotate(-5deg) translate(50px,30px); } They’re applied in the order in which they’re listed. Order matters in the final result. NOTE: If you apply a transform on an element in a different state (for example, :hover), repeat all transforms applied so far to that element or they will be overwritten. Smoothing Out Transformations Smooth out a transform using the transition property. Example: Make an element appear to rotate smoothly when the mouse moves over it or when it’s in focus: a:hover img.twist, a:focus img.twist { transform: rotate(-5deg); } img.twist { transition-property: transform; transition-duration: .3s; } 3-D Transforms You can apply perspective to element boxes to make them appear as though they’re in a 3-D space. 3-D Transforms (cont’d) • Apply the perspective property to the containing element (the lower the value, the more extreme the perspective): ul { ... perspective: 600; { • Apply one of the 3-D transform functions to each child element: li { ... transform: rotateX(45deg); { Intro to Keyframe Animation Keyframe animation enables you to create transitions between a series of states (keyframes): 1. Establish the keyframes with a @keyframes rule: @keyframes animation-name { keyframe { property: value; } /* additional keyframes */ } 2. Apply animation properties to the element(s) that will be animated. Intro to Keyframe Animation (cont’d) Keyframes establish colors at each point in the animation and give the sequence a name (“rainbow"): @keyframes rainbow { 0% { background-color: red; } 20% { background-color: orange; } 40% { background-color: yellow; } 60% { background-color: green; } 80% { background-color: blue; } 100% { background-color: purple; } } The animation properties are applied to the animated element (including which keyframe sequence to use): #magic { … animation-name: rainbow; animation-duration: 5s; animation-timing-function: linear; animation-iteration-count: infinite; animation-direction: alternate; } 19 MORE CSS TECHNIQUES OVERVIEW • Styling forms • Style properties for tables • CSS reset and normalizer • Image replacement techniques • CSS feature detection Styling Forms Use standard color, background, font, and box properties. Flexbox is a good tool for making the form adapt to available viewport space. • Text inputs Change the appearance of the box with box properties. Style the text inside the box with color and various font properties. • textarea Change font and line-height of text field. Prevent resizing with resize: none;. • Buttons (submit, reset, button) Use box and font properties. Note that the default is border-box sizing with padding applied. Styling Forms (cont’d) • Radio and checkbox buttons Best practice is to leave them alone (or substitute your own JavaScript custom buttons). • Drop-down and select menus (select) Specify the width and height. Best practice is to leave the option formatting to the browser. Some allow you to style the option text. • Fieldsets and legends Apply box properties to fieldset. The legend element is difficult to style (try styling a span inside the legend element instead). Styling Tables To add space within a cell, apply the padding property to td or th. To add space between cells, use the border-collapse and borderspacing properties. border-collapse Values: separate, collapse separate allows space between cells. collapse combines borders with no space. border-spacing Values: Horizontal-length vertical-length Specifies an amount of space between columns and rows when bordercollapse is set to separate Styling Tables (cont’d) Styling Tables (cont’d.) empty-cells Values: show, hide When borders are separate, this property indicates whether empty cells display their backgrounds and borders. caption-side Values: top, bottom Specifies on which side the caption element displays. table-layout Values: auto, fixed Calculates the width of the table based on width values (fixed) or the minimum width required for the content of the table (auto). “A Clean Slate” with CSS Reset A CSS reset is a collection of styles that overrides all user agent styles (browser defaults) and gives you a neutral starting point for your own styles. Example: An excerpt from Eric Meyer’s CSS Reset that removes margins, padding, and borders and sets the font to 100% for all elements: /* http://meyerweb.com/eric/tools/css/reset/ v2.0 | 20110126 License: none (public domain)*/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, /*... MORE ELEMENTS...*/ section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; font: inherit; vertical-align: baseline; } /* Styles continue... */ Normalize.css Normalize.css is a reset style sheet that retains some initial browser styles but tweaks them for consistency across browsers. It prevents needing to write styles for every element. Image Replacement Techniques (IRT) IRT replaces text with an image (like a logo) while ensuring it’s accessible to screen readers and search engines. There are many techniques. The “Phark” method is popular: 1. Put the image in the background of the sized text element. 2. Move the text itself out of the browser window with a large negative text-indent. NOTE: Consider whether the alt attribute on an img element may suffice before using an IRT. Phark Image Replacement Technique The markup: The style rule: <h1 id="logo">Jenware</h1> #logo { width: 450px; height: 80px; background: url(jenware.png) no-repeat; text-indent: -9999px; } CSS Sprites • A sprite is an image file that contains multiple images. • Putting many small images in one image file reduces calls to the server and improves performance. • Use the image as a background image and control which portion of it is visible with the background-position property: li a { display: block; width: 40px; height: 40px; background-image: url(social.png); } li a.twitter { background-position: 0 0;} li a.fb { background-position: 0 -40px;} li a.gplus { background-position: 0 -80px;} li a.linkedin { background-position: 0 -120px; } li a.dropbox { background-position: 0 -160px; } li a.pinterest { background-position: 0 -200px; } CSS Sprites (cont’d) CSS Feature Detection It takes a while for new CSS features to be supported in all browsers. Feature detection lets you test for support of a particular feature and provide appropriate fallbacks for nonsupporting browsers. Two common detection methods: • CSS feature queries (@supports rule) • Modernizr (JavaScript library) NOTE: In the past, styles were delivered based on the browser version. Testing for individual features is a better approach. CSS Feature Queries (@supports) A @supports rule tests for support of a particular property and value pair. If the browser passes, the rules inside the brackets are applied: @supports (property: value) { /* Style rules for supporting browsers here */ } TIP: Provide fallback styles for non-supporting browsers first and then override them with the preferred rules. CSS Feature Queries (cont’d) The mix-blend-mode property is specified for browsers that support it. Other browsers get a similar effect with the widely supported opacity property. #container { background-color: #96D4E7; padding: 5em; } .blend img { opacity: .5; } @supports (mix-blend-mode: multiply) { .blend img { mix-blend-mode: multiply; opacity: 1; } } CSS Feature Queries (cont’d) PROS: • Doesn’t rely on JavaScript • Can take advantage of cutting-edge properties safely CONS: • Limited browser support (for now) • CAUTION: Some browsers that don’t support feature queries do support newer properties you might test for (for example, Flexbox). The new properties won’t apply if they are in an unsupported @supports rule. NOTE: Feature queries are a great way to test for Grid support. Modernizr A JavaScript library that tests for HTML5 and CSS3 features. It indicates the result (support or no support) with a class name applied to the html element (and in a JavaScript object for scripting): <html class="js flexbox"> <html class="js no-flexbox"> Use the generated class name in the selector to separate styles for supporting and non-supporting browsers: .flexbox nav { /* flexbox styles for the nav element here */ } .no-flexbox nav { /* fallback styles for the nav element here */ } Modernizr (cont’d.) 1. Go to modernizr.com to build and download the Modernizer.js script. (NOTE: You can customize the script to test for just the features you need.) 2. Put the Modernizer.js file in the same directory a the files for your site. 3. Add the script to the head of the HTML document, before linked style sheets or other scripts. 4. Add class="no-js" to the html element (it gets overwritten if there is JavaScript): <html class="no-js"> <head> <script src="modernizr-custom.js"></script> <!--other scripts and style sheets --> </head> Modernizr (cont’d) PROS: • Easy to use, with thorough documentation • Excellent browser support CONS: • Relies on JavaScript (which may not be enabled) • Slightly slower than CSS feature queries 20 MODERN WEB DEVELOPMENT TOOLS OVERVIEW • Introduction to the command line • CSS preprocessors (Sass) • CSS postprocessors (PostCSS) • “Build” tools • Git version control Command-Line Interface In a command-line interface (CLI), you interact with the computer by typing commands directly into a terminal program. The program that interprets the commands you type is called a shell (bash is the shell used on Mac and Linux). Command-line tools are popular because • They are useful for file management on remote servers. • It is easier to create a command-line tool than one with a full graphical user interface (GUI). Terminal The Terminal application on Mac and Linux runs the bash shell required for many web development tools. Windows users can install the Cygwin bash emulator or install a full Linux environment. Prompts The command-line prompt is a string of characters that indicates the terminal is ready to receive a command: $:_ Prompts may also include the computer name, the working directory, and the user name: MyComputer:Sites jen$:_ When you see the prompt, type your command and hit Enter. NOTE: The underscore above indicates the cursor position (it may be a flashing line or rectangle on the screen). Commands Commands are standardized abbreviations for the task you want to perform. Type a command after the prompt. The command is executed, and a new prompt appears. Example: The ls command displays the contents of the current (working) directory: JensAir:~ jen$ ls Applications Downloads Desktop Dropbox Documents Library JensAir:~ jen$ Movies Music Pictures Public Sites Flags A flag changes how a utility operates (like an option). It follows the command name and is indicated by a single or double dash (-). Example: Adding the -l (long) flag, makes the ls command display directory contents in a longer format that includes permission settings and creation dates: JensAir:~ jen$ ls -l total 0 drwxr-xr-x 5 jen staff drwx-----57 jen staff drwx-----26 jen staff drwx------+ 151 jen staff ... drwxr-xr-x 6 jen staff drwxr-xr-x 11 jen staff JensAir:~ jen$ 170 1938 884 5134 Jul 8 2016 Applications Sep 11 09:47 Desktop May 18 11:34 Documents Sep 3 15:47 Downloads 204 May 6 374 Jul 10 2015 Public 2016 Sites Arguments An argument provides the specific information required by some functions. Example: To change to a new directory, use the cd (change directory) command as well as the name of the target directory. The directory name is the argument for the cd command. JensAir:~ jen$ cd Dropbox JensAir:Dropbox jen$_ To back up a level, use the "dot-dot" shorthand: JensAir:Dropbox jen$ cd .. JensAir:~ jen$_ A Few More Command Examples mv: Moves files and folders cp: Copies files mkdir: Creates a new empty directory rm: Removes a file or subdirectory from the working directory permanently man: Displays documentation (the manual) for a command (example: man ls shows manual for the ls command). NOTE: For a complete list of bash commands, see ss64.com/bash. CSS Preprocessors CSS preprocessors allow authors to write CSS in a syntax similar to a scripting language. The most popular preprocessor is Sass, followed by LESS and Stylus. Preprocessor syntax offers many efficiencies, including: • Nesting styles • Reusable variables • Reusable sets of styles (mixins) CSS Preprocessors (cont’d) A compiler program converts the preprocessor language to a standard .css file the browser can read: Nesting (shown in Sass syntax) Sass lets you nest style rules to match the structure of the document (it decreases the number of selectors): Sass syntax Converted to standard CSS: nav { margin: 1em 2em; ul { list-style: none; padding: 0; margin: 0; li { display: block; width: 6em; height: 2em; } } nav { margin: 1em 2em; } nav ul { list-style: none; padding: 0; margin: 0; } nav ul li { display: block; width: 6em; height: 2em; } Variables (shown in Sass syntax) A variable is a value you define once and use multiple times throughout the document. The advantage is you can change the value in one place instead of replacing it everywhere. It also helps keep styles consistent. Sass syntax: Converted to standard CSS: $oreilly-red: #900; a { border-color: #900; } a { border-color: $oreilly-red; } Mixins (shown in Sass syntax) A mixin is set of style declarations that you can define once and reuse. It eliminates a lot of repetitive code: Sass syntax: Converted to standard CSS: @mixin special { color: #fff; background-color: #befc6d; border: 1px dotted #59950c; } a.nav { @include special; } a.nav: hover { @include special; border: 1px yellow solid; } a.nav { color: #fff; background-color: #befc6d; border: 1px dotted #59950c; } a.nav: hover { color: #fff; background-color: #befc6d; border: 1px dotted #59950c; border: 1px yellow solid; } Mixins with Arguments (shown in Sass syntax) Use an argument (a placeholder value indicated with a $) in a mixin to plug different values in as needed: Sass syntax: Converted to standard CSS: @mixin rounded($radius) { -webkit-border-radius: $radius; -moz-border-radius: $radius; border-radius: $radius; } aside { @include rounded(.5em); background: #f2f5d5; } aside { -webkit-border-radius: .5em; -moz-border-radius: .5em; border-radius: .5em; background: #f2f5d5; } NOTE: This is useful for vendor prefixes, as shown in the example. Postprocessors Postprocessors take standard CSS and optimize it. The most popular postprocessor is PostCSS. This is a JavaScriptbased program (a Node.js module) with hundreds of communitycreated plug-ins that solve many CSS problems. PostCSS Examples A few examples of tasks handled by PostCSS plug-ins: • Adding vendor prefixes when needed (Autoprefixer) • Checking for CSS syntax errors (Stylelint) • Converting rem units to pixel units (Pixrem) • Generating fallbacks for cutting-edge CSS4 features (CSSNext) • Inserting hacks required for old versions of IE (Fixie) Task Runners (Build Tools) A task runner is a program that automates common production processes to make your workflow more efficient. A build tool generates web pages from multiple components, such as templates and a database. The most popular tools are Grunt and Gulp. They’re built on the open source Node.js JavaScript framework. Common Build Tool Tasks • Running CSS pre- and postprocessors • Concatenation: Assembling module-based style sheets and scripts into master files for publication • Compression and minification: Removing unnecessary whitespace and line returns to reduce file size • Optimizing images in batches to reduce file size • Committing and pushing changes to Git • Building final HTML files from templates and data Version Control with Git A version control system (VCS) • Saves versions of work that you can go back to • Allows multiple people to work on a shared set of files Git is the most popular VCS for web development. GitHub is a service that provides servers for Git projects, for free or for a fee. How Git Works • Git keeps a copy of every revision of your files and folders. • Every change (called a commit) is logged in with • A unique ID (generated by Git) • A message describing the change (written by the user) • Other metadata • All past versions and the commit log are stored in a repository (also called a repo). • Git is a distributed version control system, meaning everyone has their own copy of the repo and can work locally and offline. Git Process and Structure Working directory The directory of files on your computer in which you do your actual work Staging area Files that have been added to Git’s index but that have not yet been committed Local repository A copy of the Git repository that resides on your own computer Remote repository A copy of a repository that resides on a shared server, often serving as a master copy for a team to share Git Process and Structure (cont’d) add (staging) Making Git aware of a file so it can track it. When you add a file, it is included in the index but not yet committed. commit To log a change to the current version of the repository, usually at a logical point in the workflow push To move data from your local repo to a remote repo pull To update your local repo with data from the shared remote repo Branching A branch is a sequential series of commits. You can think of it as a thread of development. Projects usually have a primary branch called the master, which is the official version of the project. You can start a new branch to work on a particular feature or bug fix: Merging You can merge the commits from one branch into another (such as from a feature branch into the master). If Git finds conflicts (different changes to the same line of code), it gives you a report of conflicts you need to fix manually: Forking and Cloning Forking (a GitHub term) makes a copy of a GitHub repo to your GitHub account so you have your own copy to play with. Cloning means making an exact replica of a repo and everything it contains. It’s common to clone a repo from a remote server to your local computer. If you want your work to be merged into the original repo, you ask the owner to pull in your changes (called a pull request). 10 EMBEDDED MEDIA OVERVIEW • iframes • Generic object element • Video players • Audio players • Canvas Window-in-a-Window (iframe) <iframe> </iframe> • The iframe element lets you embed a separate HTML document on a page. • It displays in its own window-in-a-window (called a nested browsing context). • Commonly used to embed videos, maps, and advertising iframe (cont’d) <h1>An Inline Frame</h1> <iframe src="glossary.html" width="400" height="250"> Your browser does not support inline frames. Read the <a href="glossary.html">glossary</a>. </iframe> • The content of the iframe element is a fallback that displays if iframe is not supported. • The width and height attributes specify the size of the window in pixels. The object Element <object> </object> <param> </param> <object data="picture.svg" type="image/svg+xml"> <img src="picture.png" alt=""> </object> • A generic element for embedding media on a web page. The media may require a plug-in to run. • The data attribute points to the media file. • The type attribute is the type of media (its MIME type). • The content of the object element is a fallback if the media type isn’t supported. The object Element (cont’d) <object type="video/quicktime" data="movies/hekboy.mov" width="320" height="256"> <param name="autostart" value="false"> <param name="controller" value="true"> </object> Some media formats may require that the object contain a number of param elements that set parameters specific to that type of media. Example: Starting a video automatically or displaying player controls Embedded Video <video> </video> HTML5 introduced the video element for embedding a video player on a web page. There is also an API for controlling video play. <video src="windtunnel.mp4" width="320" height="262" poster="windtunnel_still.jpg" controls autoplay> Get the <a href="windtunnel.mp4">MP4 wind tunnel video</a> </video> Embedded Video (cont’d.) The content in the video element is a fallback for browsers that don’t support the HTML5 video element (e.g., providing a link to the video). video element attributes: • width/height: Specific dimension in pixels • poster: Provides location of still image to show before video plays • controls: Indicates that the video player controls should be visible • autoplay: Makes the video start playing automatically Video Formats • Browsers are inconsistent about which video formats they support (see table). • Best supported format: MP4 (H.264) [MPEG-4 video container, H.264 video compression, and AAC audio compression] Format Type IE MS Edge Chrome Firefox Safari Opera Android Brows er iOS Safar i MP4 (H.264) video/mp4 mp4 m4v 9.0+ 12+ 4+ Yes* 3.2+ 25+ 4.4+ 3.2+ WebM (VP8) video/webm webm webmv – – 6+ 4.0+ – 15+ 2.3+ – WebM (VP9) video/webm webm webmv – 14+ 29+ 28+ – 16+ 4.4+ – Ogg Theora video/ogg ogv – – 3.0+ 3.5+ – 13+ 2.3+ – Video Formats (cont’d.) <source> </source> To provide several video format options, list them in source elements in the video element. The browser downloads the first file it supports, so put the videos with the smallest file sizes first. <video id="video" controls poster="img/poster.jpg"> <source src="clip.webm" type="video/webm"> <source src="clip.mp4" type="video/mp4"> <source src="clip.ogg" type="video/ogg"> <a href="clip.mp4">Download the MP4 of the clip.</a> </video> Audio Players <audio> </audio> <source> </source> The audio element embeds an audio player on the page, similar to video, but with no height, width, or poster attributes: <audio id="threeoclock" controls preload="auto"> <source src="jetfighter.mp3" type="audio/mp3"> <source src="jetfighter.ogg" type="audio/ogg"> <source src="jetfighter.webm" type="audio/webm"> <p>Download <a href="jetfighter.mp3">"Jet Fighter"</a></p> </audio> Audio Formats • Browsers are inconsistent in audio format support (see table). • Best supported format: MP3 Format Type IE MP3 audio/mpeg mp3 9.0+ WAV audio/wav or audio/wave – MS Edge Chrome Firefox Opera Safari iOS Safari Android 12+ 3.0+ 22+ 15+ 4+ 12+ 8.0+ 3.5+ 11.5 4+ 3.2+ 2.3+ – – 2.3+ 4.1 2.3+ + Ogg audio/ogg ogg oga – – 4.0+ 3.5+ Vorbis MPEG- + audio/mp4 m4a 11.0 audio/webm webm – 4/AAC WebM/Vo 12+ 12.0+ – 15+ 4+ 4.1+ 3.0+ – 6.0+ 4.0+ 11.5 – – 2.3.3+ – – – + rbis WebM/O pus 11.5 + audio/webm webm – 14+ 33+ 15+ 20+ Adding Text Tracks <track> </track> The track element provides text that is synchronized with the audio or video. Useful for: • Subtitles • Captions • Descriptions for sight impaired • Chapter titles • Metadata (non-displaying) Adding Text Tracks (cont’d.) The track element goes inside the video or audio element you want to annotate. The src attribute points to a text file in .vtt format. <video width="640" height="320" controls> <source src="japanese_movie.mp4" type="video/mp4"> <source src="japanese_movie.webm" type="video/webm"> <track src="english_subtitles.vtt" kind="subtitles" srclang="en" label="English subtitles" default> <track src="french.vtt" kind="subtitles" srclang="fr" label="Sous-titres en français"> </video> Canvas <canvas> </canvas> • The canvas element embeds a 2-D bitmapped drawing area that is controlled by JavaScript functions. • It is useful for games and drawing interfaces. muro.deviantart.com majong.frvr.com Canvas (cont’d) A sample of the JavaScript used to draw this simple graphic. //draw face my_canvas.beginPath(); my_canvas.arc(100, 100, 75, (Math.PI/180)*0, (Math.PI/180)*360, false); // circle dimensions my_canvas.strokeStyle = "black"; // circle outline is black my_canvas.lineWidth = 3; // outline is three pixels wide my_canvas.fillStyle = "yellow"; // fill circle with yellow my_canvas.stroke(); // draw circle my_canvas.fill(); // fill in circle my_canvas.closePath(); 21 INTRODUCTION TO JAVASCRIPT OVERVIEW • What JavaScript is • Variables and arrays • if/else statements and loops • Native and custom functions • Browser objects • Event handlers What Is JavaScript? • JavaScript is a client-side scripting language—it is processed on the user’s machine (not the server). • It is reliant on the browser’s capabilities (it may even be unavailable entirely). • It is a dynamic programming language—it does not need to be compiled into an executable program. The browser reads it just as we do. • It is loosely typed—you don’t need to define variable types as you do for other programming languages. JavaScript Tasks JavaScript adds a behavioral layer (interactivity) to a web page. Some examples include: • Checking form submissions and provide feedback messages and UI changes • Injecting content into current documents on the fly • Showing and hiding content based on a user clicking a link or heading • Completing a term in a search box • Testing for browser features and capabilities • Much more! Adding Scripts to a Page Embedded script Include the script in an HTML document with the script element: <script> … JavaScript code goes here </script> External script Use the src attribute in the script element to point to an external, standalone .js file: <script src="my_script.js"></script> Script Placement The script element can go anywhere in the document, but the most common places are as follows: In the head of the document Just before the </body> tag For when you want the script to do something before the body completely loads (ex: Modernizr): Preferred when the browser needs to parse the document and its DOM structure before running the script: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script src="script.js"></script> </head> ... ... <body> <!--contents of page--> <script src="script.js"></script> </body> </html> JavaScript Syntax Basics • JavaScript is case-sensitive. • Whitespace is ignored (unless it is enclosed in quotes in a text string). • A script is made up of a series of statements, commands that tell the browser what to do. • Single-line comments in JavaScript appear after two // characters: // This is a single-line comment • Multiple-line comments go between /* and */ characters. Building Blocks of Scripts • Variables • Comparison operators • if/else statements • Loops • Functions • Scope Variables • A variable is made up of a name and a value. • You create a variable so that you can refer to the value by name later in the script. • The value can be a number, text string, element in the DOM, or function, to name a few examples. • Variables are defined using the var keyword: var foo = 5; The variable is named foo. The equals sign (=) indicates we are assigning it the numeric value of 5. Variables (cont’d) Rules for naming a variable: • It must start with a letter or underscore. • It may not contain character spaces. Use underscores or CamelCase instead. • It may not contain special characters (! . , / \ + * =). • It should describe the information it contains. Value Data Types Values assigned to variables fall under a few data types: Undefined The variable is declared by giving it a name, but no value: var foo; alert(foo); // Will open a dialog containing "undefined" null Assigns the variable no inherent value: var foo = null; alert(foo); // Will open a dialog containing "null" Numbers When you assign a number (e.g., 5), JavaScript treats it as a number (you don’t need to tell it it's a number): var foo = 5; alert(foo + foo); // This will alert "10" Value Data Types (cont’d) Strings If the value is wrapped in single or double quotes, it is treated as a string of text: var foo = "five"; alert(foo); // Will alert "five" alert(foo + foo); // Will alert "fivefive" Booleans Assigns a true or false value, used for scripting logic: var foo = true; // The variable "foo" is now true Arrays A group of multiple values (called members) assigned to a single variable. Values in arrays are indexed (assigned a number starting with 0). You can refer to array values by their index numbers: var foo = [5, "five", "5"]; alert( foo[0] ); // Alerts "5" alert( foo[1] ); // Alerts "five" alert( foo[2] ); // Also alerts "5" Comparison Operators Comparison operators are special characters in JavaScript syntax that evaluate and compare values: == Is equal to != Is not equal to === Is identical to (equal to and of the same data type) !== Is not identical to > Is greater than >= Is greater than or equal to < Is less than <= Is less than or equal to Comparison Operators (cont’d) Example When we compare two values, JavaScript evaluates the statement and gives back a Boolean (true/false) value: alert( 5 == 5 ); // This will alert "true" alert( 5 != 6 ); // This will alert "true" alert( 5 < 1 ); // This will alert "false" NOTE: Equal to (==) is not the same as identical to (===). Identical values must share a data type: alert( "5" == 5 ); // This will alert "true". They're both "5". alert( "5" === 5 ); // This will alert "false". They're both "5", but they're not the same data type. alert( "5" !== 5 ); // This will alert "true", since they're not the same data type. Mathematical Operators Mathematical operators perform mathematical functions on numeric values: + Add - Subtract * Multiply / Divide += Adds the value to itself ++ Increases the value of a number (or number in a variable) by 1 -- Decreases the value of a number (or number in a variable) by 1 if/else Statements An if/else statement tests for conditions by asking a true/false question. If the condition in parentheses is met, then execute the commands between the curly brackets ({}): if(true) { // Do something. } Example: if( 1 != 2 ) { alert("These values are not equal."); // It is true that 1 is never equal to 2, so we should see this alert. } if/else Statements (cont’d) If you want to do one thing if the test is true and something else if it is false, include an else statement after the if statement: var test = "testing"; if( test == "testing" ) { alert( "You haven't changed anything." ); } else { alert( "You've changed something!" ); } Changing the value of the test variable to anything but the word “testing” will trigger the alert “You've changed something!” Loops Loops allow you to do something to every variable in an array without writing a statement for every one. One way to write a loop is with a for statement: for(initialize variable; test condition; alter the value;) { // do something } Loops (cont’d) Example: This loop triggers 3 alerts, reading "0", "1", and “2": for(var i = 0, i <= 2, i++) { alert(i); } • for(): Says, "for every time this is true, do this.” • var i = 0: Creates a new variable i with its value set to 0. "i" (short for “index”) is a common variable name. • i <= 2: Says, “as long as i is less than or equal to 2, keep looping.” • i++: Shorthand for “every time this loop runs, add 1 to the value of i.” • {alert(i);}: This loop will run three times (once each for 0, 1, and 2 values) and alert the i value. Functions A function is a bit of code for performing a task that doesn’t run until it is referenced or called. Parentheses sometimes contain arguments (additional information used by the function): Functions (cont’d) Some functions are built into JavaScript. Here are examples of native functions: • alert(), confirm(), and prompt() Functions that trigger browser-level dialog boxes • Date() Returns the current date and time You can also create your own custom functions by typing function followed by a name for the function and the task it performs: function name() { // Code for the new function goes here. } Variable Scope A variable that can only be used within one function is locally scoped. When you define a variable inside a function, include the var keyword to keep it locally scoped (recommended): var foo = "value"; A variable that can be used by any script on your page is said to be globally scoped. • Any variable created outside of a function is automatically globally scoped: var foo = "value"; • To make a variable created inside a function globally scoped, omit the var keyword: foo = "value"; The Browser Object JavaScript lets you manipulate parts of the browser window itself (the window object). Examples of window properties and methods: Property/Method Description event Represents the state of an event history Contains the URLs the user has visited within a browser window location Gives read/write access to the URI in the address bar status Sets or returns the text in the status bar of the window alert() Displays an alert box with a specified message and an OK button close() Closes the current window confirm() Displays a dialog box with a specified message and an OK and a Cancel button focus() Sets focus on the current window Event Handlers An event is an action that can be detected with JavaScript and used to trigger scripts. Events are identified by event handlers. Examples: When the page loads • onload • onclick • onmouseover • onerror When an error occurs when the document or a resource loads When the mouse clicks an object When the pointer is moved over an element Event Handlers (cont’d) Event handlers can be applied to items in pages in three ways: • As an HTML attribute: <body onclick="myFunction();"> /* myFunction runs when the within 'body' */ • user clicks anything As a method attached to the element: window.onclick = myFunction; /* myFunction will run when the user clicks anything within the browser window */ • Using addEventListener(): window.addEventListener("click", myFunction); Notice that we omit the preceding “on” from the event handler with this syntax.