Advanced CSS – P2 – Cheat Sheet

Advanced CSS – Part 1 | Advanced CSS – Part 2


JQuery

https://learn.shayhowe.com/advanced-html-css/jquery/

In part of being a web designer or front end developer you will commonly run into JavaScript, often referred to as JS, and jQuery. Within the top 10,000 websites JavaScript is used within over 92% of them, and jQuery is used within in over 63% of them. Needless to say, they are fairly popular. You may even aspire to write JavaScript or jQuery to build your own behaviors at one point or another.

If you are asking what exactly are JavaScript and jQuery fear not, this lesson gives a brief overview of JavaScript and then takes a look at jQuery.

JavaScript Intro

JavaScript provides the ability to add interactivity to a website, and help enrich the user experience. HTML provides a page with structure and CSS provides a page with appearance, JavaScript provide a page with behavior.

Like CSS, JavaScript should be saved in an external file with the .js file extension, and then referenced within an HTML document using the script element. Where the JavaScript reference is placed with HTML depends on when it should be executed. Generally speaking, the best place to reference JavaScript files is right before the closing </body> tag so that the JavaScript file is loaded after all of the HTML has been parsed. However, at times, JavaScript is needed to help render HTML and determine it’s behavior, thus may be referenced within a documents head.

1 2<script src="script.js"></script>               

Values & Variables

Part of the fundamentals of JavaScript include values and variables. Values, in general, are the different types of values that JavaScript will recognize, while variables are used to store and share these values.

Values may include strings of text, true or false Booleans, numbers, undefined, null, or other values such as functions or objects.

One popular way variables are defined is with the var keyword, followed by the variable name, an equal sign (=), then the value, ending with a semicolon (;). The variable name must begin with a letter, underscore (_), or dollar sign ($). Variables cannot begin with numbers, although they may be used subsequently, and they cannot use hyphens whatsoever. Additionally, JavaScript is case sensitive so letters include a through z in both lower and uppercase.

The common convention around naming variables is to use camelCase, without the use of any dashes or underscores. camelCase consist of combining words while removing spaces, capitalizing the beginning of each new word except for the initial word. For example, shay_is_awesome would more commonly named shayIsAwesome.

1 2 3 4 5var theStarterLeague = 125; var food_truck = 'Coffee'; var mixtape01 = true; var vinyl = ['Miles Davis', 'Frank Sinatra', 'Ray Charles'];               

Statements

As a whole, JavaScript is a set of statements, of which are executed by the browser in the sequence they are written. These statements provide commands which determine the different behaviors to be taken. Statements come in all different shapes and sizes, with multiple statements separated with semicolons, ;. New statements should begin on a new line, and indentation should be used when nesting statements for better legibility, but is not required.

1 2 3 4log(polaroid); return('bicycle lane'); alert('Congratulations, you ' + outcome);               

Functions

Adding to the fundamentals of JavaScript, it is important to take a look at functions. Functions provide a way to perform a set of scripted behaviors now, or saved for later, and depending on the function they may even accept different arguments.

A function is defined by using the function keyword followed by the function name, a list of commas separated arguments wrapped in parentheses, if necessary, and then the JavaScript statement, or statements, that defines the function enclosed in curly braces, {}.

1 2 3 4function sayHello(name) {  return('Hello ' + name); }               

Arrays

As you may have recognized, some values may be returned as an array. Arrays include a way to store a list of items, or values. Arrays are helpful for many reasons, one being the ability to be traversed with different methods and operators. Additionally, depending on the situation, arrays can be used to store, and return, a variety of different values.

Generally speaking arrays are identified within square brackets, [], with comma separated items. The items start at 0 and increase from there. When identifying the third item in a list it is actually identified as [2].

Objects

JavaScript is also built on the foundation of objects, which are a collection of key and value pairs. For example, there may be an object named school which includes the keys, also known as properties, name, location, students, and teachers, and their values.

In the example below the variable school is set up as an object to hold multiple properties. Each property has a key and value. The entire object is wrapped inside of curly braces, {}, with comma separated properties, each having a key followed by a colon and value.

1 2 3 4 5 6 7 8 9 10 11// Object var school = {  name: 'The Starter League',  location: 'Merchandise Mart',  students: 120,  teachers: ['Jeff', 'Raghu', 'Carolyn', 'Shay'] }; // Array var school = ['Austin', 'Chicago', 'Portland'];               

Web Inspector Console

Fig. 6

Using the developer tools built into the Chrome web browser, JavaScript may be run from within the console.

jQuery Intro

With a basic understanding of JavaScript and some of it’s foundations, it is time to take a look at jQuery. jQuery is an open source JavaScript library written by John Resig that simplifies the interaction between HTML, CSS, and JavaScript. Since 2006, when jQuery was released, it has taken off, being used by websites and companies large and small.

What has made jQuery so popular is it’s ease of use, with selections resembling CSS and a comprehensible separation of behavior. The benefits of jQuery are massive, however for our purpose we will only be considered about the ability to find elements and perform actions with them.

Getting Started with jQuery

The first step to using jQuery is to reference it from within a HTML document. As previously mentioned with JavaScript, this is done using the script element just before the closing </body> tag. Since jQuery is it’s own library it is best to keep it separate from all the other JavaScript being written.

When referencing jQuery there are a few options, specifically as whether to use the minified or uncompressed version, and as whether to use a content delivery network, CDN, such as Google hosted libraries. If the code being written is for a live, production environment it is encouraged to use the minified version for better loading times. Additionally, using a CDN like Google also helps with loading time, and potential caching benefits.

1 2 3<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script src="script.js"></script>               

In the code sample above, notice the second script element referencing a second JavaScript file. All of the custom, handwritten JavaScript and jQuery should be written in this file. Additionally, this file is specifically placed after the jQuery file so that it may reference jQuery functions already defined.

Where is the leading http?

You may have noticed that there isn’t a leading http within Google CDN reference example above. The http has been omitted intentionally to allow for both http and https connections. When working locally, without the benefit of a web server, the leading http will need to be included to prevent attempting to locate the file on the systems local disk drive.

jQuery Object

jQuery comes with it’s own object, the dollar sign, $, also known as jQuery. The $ object is specifically made for selecting an element and then returning that element node to perform an action on it. These selections and actions should be written in a new file, referenced outside of the actual jQuery library.

1 2 3$(); jQuery();               

Document Ready

Before trigging any jQuery to traverse and manipulate a page it is best to wait until the DOM is finished loading. Fortunately jQuery has a ready event, .ready(), which can be called when the HTML document is ready to be altered. By placing all of our other custom written jQuery inside of this function we can guarantee that it will not be executed until the page has loaded and the DOM is ready.

1 2 3 4$(document).ready(function(event){   // jQuery code  });               

Selectors

As previously mentioned, one of the core concepts of jQuery is to select elements and perform an action. jQuery has done a great job of making the task of selecting an element, or elements, extremely easy by mimicking that of CSS. On top of the general CSS selectors, jQuery has support for all of the unique CSS3 selectors, which work regardless of which browser is being used.

Invoking the jQuery object, $(), containing a selector will return that DOM node to manipulate it. The selector falls within the parentheses, ('...'), and may select elements just like that of CSS.

1 2 3 4 5 6$('.feature');           // Class selector $('li strong');          // Descendant selector $('em, i');              // Multiple selector $('a[target="_blank"]'); // Attribute selector $('p:nth-child(2)');     // Pseudo-class selector               

This Selection Keyword

When working inside of a jQuery function you may want to select the element in which was referenced inside of the original selector. In this event the this keyword may be used to refer to the element selected in the current handler.

1 2 3 4$('div').click(function(event){   $(this); });               

jQuery Selection Filters

Should CSS selectors not be enough there are also custom filters built into jQuery to help out. These filters are an extension to CSS3 and provide more control over selecting an element or its relatives.

1 2$('div:has(strong)');                 

As they stand these filters may be used inside of the selector, however not being native to the DOM they are a bit slow. The best results with using these filters is accomplished by using the :filter() method, which is part of the traversing feature in jQuery.

Traversing

At times the general CSS selectors alone don’t cut it and a little more detailed control is desired. Fortunately jQuery provides a handful of methods for traversing up and down the DOM tree, filtering and selecting elements as necessary.

To get started with filtering elements inside the DOM a general selection needs to be made, from which will be traversed from relatively. In the example below the original selection finds all of the div elements in the DOM, which are then filtered using the .not() method. With this specific method all of the div elements without a class of type or collection will be selected.

1 2$('div').not('.type, .collection');               

Chaining Methods

For even more control as to which elements are selected different traversing methods may be chained together simply by using a dot in-between them.

The code sample below uses both the .not() method and the .parent() method. Combined together this will only select the parent elements of div elements without a class of type or collection.

1 2$('div').not('.type, .collection').parent();               

Traversing Methods

jQuery has quite a few traversing methods available to use. In general, they all fall into three categories, filtering, miscellaneous traversing, and DOM tree traversing. The specific methods within each category may be seen below.

Filtering

  • .eq()
  • .filter()
  • .first()
  • .has()
  • .is()
  • .last()
  • .map()
  • .not()
  • .slice()

Miscellaneous Traversing

  • .add()
  • .andSelf()
  • .contents()
  • .end()

DOM Tree Traversal

  • .children()
  • .closest()
  • .find()
  • .next()
  • .nextAll()
  • .nextUntil()
  • .offsetParent()
  • .parent()
  • .parents()
  • .parentsUntil()
  • .prev()
  • .prevAll()
  • .prevUntil()
  • .siblings()

Manipulation

Selecting and traversing elements in the DOM is only part of what jQuery offers, one other major part is what is possible with those elements once found. One possibility is to manipulate these elements, by either reading, adding, or changing attributes or styles. Additionally, elements may be altered in the DOM, changing their placement, removing them, adding new elements, and so forth. Overall the options to manipulate elements are fairly vast.

Getting & Setting

The manipulation methods to follow are most commonly used in one of two directives, that being getting or setting information. Getting information revolves around using a selector in addition with a method to determine what piece of information is to be retrieved. Additionally, the same selector and method may also be used to set a piece of information.

1 2 3 4 5 6// Gets the value of the alt attribute $('img').attr('alt'); // Sets the value of the alt attribute $('img').attr('alt', 'Wild kangaroo');               

In the examples and snippets to follow methods will primarily be used in a setting mode, however they may also be able to be used in a getting mode as well.

Attribute Manipulation

One part of elements able to be inspected and manipulated are attributes. A few options include the ability to add, remove, or change an attribute or its value. In the examples below the .addClass() method is used to add a class to all even list items, the .removeClass() method is used to remove all classes from any paragraphs, and lastly the .attr() method is used to find the value of the title attribute of any abbr element and set it to Hello World.

1 2 3 4$('li:even').addClass('even-item'); $('p').removeClass(); $('abbr').attr('title', 'Hello World');               

Attribute Manipulation Methods

  • .addClass()
  • .attr()
  • .hasClass()
  • .prop()
  • .removeAttr()
  • .removeClass()
  • .removeProp()
  • .toggleClass()
  • .val()

Style Manipulation

On top of manipulating attributes, the style of an element may also be manipulated using a variety of methods. When reading or setting the height, width, or position of an element there are a handful of special methods available, and for all other style manipulations the .css() method can handle any CSS alterations.

The .css() method in particular may be used to set one property, or many, and the syntax for each varies. To set one property, the property name and value should each be in quotations and comma separated. To set multiple properties, the properties should be nested inside of curly brackets with the property name in camel case, removing any hyphens where necessary, followed by a colon and then the quoted value. Each of the property and value pairs need to be comma separated.

The height, width, or position methods all default to using pixel values, however other units of measurement may be used. As seen below, to change the unit of measurement identify the value then use a plus sign followed by the quoted unit of measurement.

1 2 3 4 5 6 7 8$('h2 span').css('font-size', 'normal'); $('div').css({  fontSize: '13px',   background: '#f60' }); $('header').height(200); $('.extend').height(30 + 'em');               

Style Manipulation Methods

  • .css()
  • .height()
  • .innerHeight()
  • .innerWidth()
  • .offset()
  • .outerHeight()
  • .outerWidth()
  • .position()
  • .scrollLeft()
  • .scrollTop()
  • .width()

DOM Manipulation

Lastly, we are able to inspect and manipulate the DOM, changing the placement of elements, adding and removing elements, as well as flat out altering elements. The options here are deep and varied, allowing for any potential changes to be made inside the DOM.

Each individual DOM manipulation method has it’s own syntax but a few of them are outlined below. The .prepend() method is adding a new h3 element just inside any section, the .after() method is adding a new em element just after the link, and the .text() method is replacing the text of any h2 elements with the text Hello World.

1 2 3 4$('section').prepend('<h3>Featured</h3>'); $('a[target="_blank"]').after('<em>New window.</em>'); $('h2').text('Hello World');               

DOM Manipulation Methods

  • .after()
  • .append()
  • .appendTo()
  • .before()
  • .clone()
  • .detach()
  • .empty()
  • .html()
  • .insertAfter()
  • .insertBefore()
  • .prepend()
  • .prependTo()
  • .remove()
  • .replaceAll()
  • .replaceWith()
  • .text()
  • .unwrap()
  • .wrap()
  • .wrapAll()
  • .wrapInner()

Events

One of the beauties of jQuery is the ability to easily add event handlers, which are methods that are called only upon a specific event or action taking place. For example, the method of adding a class to an element can be set to only occur upon that element being clicked on.

Below is a standard selector, grabbing all of the list items. The .click() event method is bound to the list item selector, setting up an action to take place upon clicking any list item. Inside the .click() event method is a function, which ensures any actions inside the event method are to be executed. The parentheses directly after the function are available to pass in parameters for the function, in which the event object is used in this example.

Inside of the function is another selector with the .addClass() method bound to it. Now, when a list item is clicked on that list item, via the this keyword, receives the class of saved-item.

1 2 3 4$('li').click(function(event){  $(this).addClass('saved-item'); });               

Event Flexibility

The .click() event method, along with a handful of other event methods, is actually a shorthand method which uses the .on() method introduced in jQuery 1.7. The .on() method provides quite a bit of flexibility, using automatic delegation for elements that get added to the page dynamically.

Making use of the .on() method the first argument should be the native event name while the second argument should be the event handler function. Looking at the example from before, the .on() method is called in place of the .click() method. Now the click event name is passed in as the first argument inside the .on() method with the event handler function staying the same as before.

1 2 3 4$('li').on('click', function(event){  $(this).addClass('saved-item'); });               

Nesting Events

It is possible to have multiple event handlers and triggers, nesting one inside another. As an example, below the .on() event method is passed the hover argument, thus being called when hovering over any element with the class of pagination. Upon calling the .on() event the .click() event is called on the anchor with the up ID.

1 2 3 4$('.pagination').on('hover', function(event){  $('a#up').click(); });               

Event Demo

Using an alert message as a demo, the following code snippets show how to create an alert message and then removing that message based upon clicking the close icon.

HTML
1 2 3 4 5<div class="notice-warning">  <div class="notice-close">×</div>  <strong>Warning!</strong> I’m about to lose my cool. </div>                 
JavaScript
1 2 3 4$('.notice-close').on('click', function(event){  $('.notice-warning').remove(); });                 

Demo

Event Methods

jQuery provides quite a few methods, all of which are based around registering user behaviors as they interact with the browser. These methods register quite a few events, most popularly, but not limited to, browser, form, keyboard, and mouse events. The most popular of these methods include:

Browser Events

  • .resize()
  • .scroll()

Document Loading

  • .ready()

Event Handler Attachment

  • .off()
  • .on()
  • .one()
  • jQuery.proxy()
  • .trigger()
  • .triggerHandler()
  • .unbind()
  • .undelegate()

Event Object

  • event.currentTarget
  • event.preventDefault()
  • event.stopPropagation()
  • event.target
  • event.type

Form Events

  • .blur()
  • .change()
  • .focus()
  • .select()
  • .submit()

Keyboard Events

  • .focusin()
  • .focusout()
  • .keydown()
  • .keypress()
  • .keyup()

Mouse Events

  • .click()
  • .dblclick()
  • .focusin()
  • .focusout()
  • .hover()
  • .mousedown()
  • .mouseenter()
  • .mouseleave()
  • .mousemove()
  • .mouseout()
  • .mouseover()
  • .mouseup()

Effects

Next to events, jQuery also provides a handful of customizable effects. These effects come by the way of different methods, including event methods for showing and hiding content, fading content in and out, or sliding content up and down. All of these are ready to use methods and may be customized as best see fit.

Each effect method has it’s own syntax so it is best to reference the jQuery effects documentation for specific syntax around each method. Most commonly though, effects generally accept a duration, easing, and the ability to specify a callback function.

jQuery CSS Animations

Custom animations of different CSS properties can be accomplished in jQuery, although this is a little less relevant as CSS can now handle animations itself. CSS animations offer better performance from a browser processing standpoint and are preferred where possible. jQuery animation effects, with the help of Modernizr, make for a perfect backup solution to any browser not supporting CSS animations.

Effect Duration

Using the .show() method as an example, the first parameter available to optionally pass in to the method is the duration, which can be accomplished using a keyword or milliseconds value. The keyword slow defaults to 600 milliseconds, while the keyword fast defaults to 200 milliseconds. Using a keyword value is fine, but millisecond values may also be passed in directly. Keyword values must be quoted while millisecond values do not.

1 2 3 4$('.error').show(); $('.error').show('slow'); $('.error').show(500);               

Effect Easing

In addition to setting the duration in which an effect takes place the easing, or speed at which an animation progresses at during different times within the animation, may also be set. By default jQuery has two keyword values for easing, the default value is swing with the additional value being linear. The default swing value starts the animation at a slow pace, picking up speed during the animation, and then slows down again before completion. The linear value runs the animation at one constant pace for the entire duration.

1 2 3$('.error').show('slow', 'linear'); $('.error').show(500, 'linear');               

jQuery UI

The two easing values that come with jQuery may be extend with the use of different plug-ins, of which may offer additional values. One of the most popular plug-ins is the jQuery UI suite.

On top of new easing values jQuery UI also provides a handful other interactions, effects, widgets, and other helpful resources worth taking a look at.

Effect Callback

When an animation is completed it is possible to run another function, called a callback function. The callback function should be placed after the duration or easing, if either exist. Inside this function new events or effects may be placed, each following their own required syntax.

1 2 3 4$('.error').show('slow', 'linear', function(event){  $('.error .status').text('Continue'); });               

Effect Syntax

As previously mentioned, each effect method has it’s own syntax which can be found in the jQuery effects documentation. The duration, easing, and callback parameters outlined here are common, but not available on every method. It is best to review the syntax of a method should you have any questions around it.

Effects Demo

Taking the same events demo from above, the .remove() method is now used as part of a callback function on the .fadeOut() method. Using the .fadeOut() method allows for the alert message to gradually fade out rather than quickly disappearing, then be removed from the DOM after the animation is complete.

HTML
1 2 3 4 5<div class="notice-warning">  <div class="notice-close">×</div>  <strong>Warning!</strong> I’m about to lose my cool. </div>                 
JavaScript
1 2 3 4 5 6$('.notice-close').on('click', function(event){  $('.notice-warning').fadeOut('slow', function(event){    $(this).remove();  }); });                 

Demo

Basic Effects

  • .hide()
  • .show()
  • .toggle()

Custom Effects

  • .animate()
  • .clearQueue()
  • .delay()
  • .dequeue()
  • jQuery.fx.interval
  • jQuery.fx.off
  • .queue()
  • .stop()

Fading Effects

  • .fadeIn()
  • .fadeOut()
  • .fadeTo()
  • .fadeToggle()

Sliding Effects

  • .slideDown()
  • .slideToggle()
  • .slideUp()

Slide Demo

HTML
1 2 3 4 5<div class="panel">  <div class="panel-stage"></div>  <a href="#" class="panel-tab">Open <span>▼</span></a> </div>                 
JavaScript
1 2 3 4 5 6 7 8 9 10 11$('.panel-tab').on('click', function(event){  event.preventDefault();  $('.panel-stage').slideToggle('slow', function(event){    if($(this).is(':visible')){      $('.panel-tab').html('Close <span>▲</span>');    } else {      $('.panel-tab').html('Open <span>▼</span>');    }  }); });                 

Demo

Tabs Demo

HTML

1 2 3 4 5 6 7 8 9

JavaScript

1 2 3 4 5 6 7 8 9 10 11 12 13 14// Show the first tab by default $('.tabs-stage div').hide(); $('.tabs-stage div:first').show(); $('.tabs-nav li:first').addClass('tab-active'); // Change tab class and display content $('.tabs-nav a').on('click', function(event){ event.preventDefault(); $('.tabs-nav li').removeClass('tab-active'); $(this).parent().addClass('tab-active'); $('.tabs-stage div').hide(); $($(this).attr('href')).show(); });

Demo


Transforms

https://learn.shayhowe.com/advanced-html-css/css-transforms/

With CSS3 came new ways to position and alter elements. Now general layout techniques can be revisited with alternative ways to size, position, and change elements. All of these new techniques are made possible by the transform property.

The transform property comes in two different settings, two-dimensional and three-dimensional. Each of these come with their own individual properties and values.

Within this lesson we’ll take a look at both two-dimensional and three-dimensional transforms. Generally speaking, browser support for the transform property isn’t great, but it is getting better every day. For the best support vendor prefixes are encouraged, however you may need to download the nightly version of Chrome to see all of these transforms in action.

Transform Syntax

The actual syntax for the transform property is quite simple, including the transform property followed by the value. The value specifies the transform type followed by a specific amount inside parentheses.

1 2 3 4 5 6 7div {  -webkit-transform: scale(1.5);     -moz-transform: scale(1.5);       -o-transform: scale(1.5);          transform: scale(1.5); }               

Notice how the transform property includes multiple vendor prefixes to gain the best support across all browsers. The un-prefixed declaration comes last to overwrite the prefixed versions, should a browser fully support the transform property.

In the interest of brevity, the remainder of this lesson will not include vendor prefixes. They are, however, strongly encouraged for any code in a production environment. Over time we will be able to remove these prefixes, however keeping them in is the safest approach for the time being.

2D Transforms

Elements may be distorted, or transformed, on both a two-dimensional plane or a three-dimensional plane. Two-dimensional transforms work on the x and y axes, known as horizontal and vertical axes. Three-dimensional transforms work on both the x and y axes, as well as the z axis. These three-dimensional transforms help define not only the length and width of an element, but also the depth. We’ll start by discussing how to transform elements on a two-dimensional plane, and then work our way into three-dimensional transforms.

2D Rotate

The transform property accepts a handful of different values. The rotate value provides the ability to rotate an element from 0 to 360 degrees. Using a positive value will rotate an element clockwise, and using a negative value will rotate the element counterclockwise. The default point of rotation is the center of the element, 50% 50%, both horizontally and vertically. Later we will discuss how you can change this default point of rotation.

HTML
1 2 3<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure>               
CSS
1 2 3 4 5 6 7.box-1 {  transform: rotate(20deg); } .box-2 {  transform: rotate(-55deg); }               

Rotate Demo

The gray box behind the rotated element symbolizes the original position of the element. Additionally, upon hover the box will rotate 360 degrees horizontally. As the lesson progresses, keep an eye out for the gray box within each demonstration as a reference to the element’s original position and the horizontal rotation to help demonstrate an elements alteration and depth.

2D Scale

Using the scale value within the transform property allows you to change the appeared size of an element. The default scale value is 1, therefore any value between .99 and .01 makes an element appear smaller while any value greater than or equal to 1.01 makes an element appear larger.

HTML
1 2 3<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure>               
CSS
1 2 3 4 5 6 7.box-1 {  transform: scale(.75); } .box-2 {  transform: scale(1.25); }               

Scale Demo

It is possible to scale only the height or width of an element using the scaleX and scaleY values. The scaleX value will scale the width of an element while the scaleY value will scale the height of an element. To scale both the height and width of an element but at different sizes, the x and y axis values may be set simultaneously. To do so, use the scale transform declaring the x axis value first, followed by a comma, and then the y axis value.

HTML
1 2 3 4<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure> <figure class="box-3">Box 3</figure>               
CSS
1 2 3 4 5 6 7 8 9 10.box-1 {  transform: scaleX(.5); } .box-2 {  transform: scaleY(1.15); } .box-3 {  transform: scale(.5, 1.15); }               

Multiple Scaling Demo

2D Translate

The translate value works a bit like that of relative positioning, pushing and pulling an element in different directions without interrupting the normal flow of the document. Using the translateX value will change the position of an element on the horizontal axis while using the translateY value will change the position of an element on the vertical axis.

As with the scale value, to set both the x and y axis values at once, use the translate value and declare the x axis value first, followed by a comma, and then the y axis value.

The distance values used within the translate value may be any general length measurement, most commonly pixels or percentages. Positive values will push an element down and to the right of its default position while negative values will pull an element up and to the left of its default position.

HTML
1 2 3 4<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure> <figure class="box-3">Box 3</figure>               
CSS
1 2 3 4 5 6 7 8 9 10.box-1 {  transform: translateX(-10px); } .box-2 {  transform: translateY(25%); } .box-3 {  transform: translate(-10px, 25%); }               

Translate Demo

2D Skew

The last transform value in the group, skew, is used to distort elements on the horizontal axis, vertical axis, or both. The syntax is very similar to that of the scale and translate values. Using the skewX value distorts an element on the horizontal axis while the skewY value distorts an element on the vertical axis. To distort an element on both axes the skew value is used, declaring the x axis value first, followed by a comma, and then the y axis value.%p

The distance calculation of the skew value is measured in units of degrees. Length measurements, such as pixels or percentages, do not apply here.

HTML
1 2 3 4<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure> <figure class="box-3">Box 3</figure>               
CSS
1 2 3 4 5 6 7 8 9 10.box-1 {  transform: skewX(5deg); } .box-2 {  transform: skewY(-20deg); } .box-3 {  transform: skew(5deg, -20deg); }               

Skew Demo

Combining Transforms

It is common for multiple transforms to be used at once, rotating and scaling the size of an element at the same time for example. In this event multiple transforms can be combined together. To combine transforms, list the transform values within the transform property one after the other without the use of commas.

Using multiple transform declarations will not work, as each declaration will overwrite the one above it. The behavior in that case would be the same as if you were to set the height of an element numerous times.

HTML
1 2 3<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure>               
CSS
1 2 3 4 5 6 7.box-1 {  transform: rotate(25deg) scale(.75); } .box-2 {  transform: skew(10deg, 20deg) translateX(20px); }               

Combining Transforms Demo

Behind every transform there is also a matrix explicitly defining the behavior of the transform. Using the rotate, scale, transition, and skew values provide an easy way to establish this matrix. However, should you be mathematically inclined, and prefer to take a deeper dive into transforms, try your hand at using the matrix property.

2D Cube Demo

HTML
1 2 3 4 5 6<div class="cube">  <figure class="side top">1</figure>  <figure class="side left">2</figure>  <figure class="side right">3</figure> </div>                 
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21.cube {  position: relative; } .side {  height: 95px;  position: absolute;  width: 95px; } .top {  background: #9acc53;  transform: rotate(-45deg) skew(15deg, 15deg); } .left {  background: #8ec63f;  transform: rotate(15deg) skew(15deg, 15deg) translate(-50%, 100%); } .right {  background: #80b239;  transform: rotate(-15deg) skew(-15deg, -15deg) translate(50%, 100%); }                 

Demo

Transform Origin

As previously mentioned, the default transform origin is the dead center of an element, both 50% horizontally and 50% vertically. To change this default origin position the transform-origin property may be used.

The transform-origin property can accept one or two values. When only one value is specified, that value is used for both the horizontal and vertical axes. If two values are specified, the first is used for the horizontal axis and the second is used for the vertical axis.

Individually the values are treated like that of a background image position, using either a length or keyword value. That said, 0 0 is the same value as top left, and 100% 100% is the same value as bottom right. More specific values can also be set, for example 20px 50px would set the origin to 20 pixels across and 50 pixels down the element.

HTML
1 2 3 4 5<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure> <figure class="box-3">Box 3</figure> <figure class="box-4">Box 3</figure>               
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17.box-1 {  transform: rotate(15deg);  transform-origin: 0 0; } .box-2 {  transform: scale(.5);  transform-origin: 100% 100%; } .box-3 {  transform: skewX(20deg);  transform-origin: top left; } .box-4 {  transform: scale(.75) translate(-10px, -10px);  transform-origin: 20px 50px; }               

Transform Origin Demo

Notably, the transform-origin property does run into some issues when also using the translate transform value. Since both of them are attempting to position the element, their values can collide. Use the two of these with caution, always checking to make sure the desired outcome is achieved.

Perspective

In order for three-dimensional transforms to work the elements need a perspective from which to transform. The perspective for each element can be thought of as a vanishing point, similar to that which can be seen in three-dimensional drawings.

The perspective of an element can be set in two different ways. One way includes using the perspective value within the transform property on individual elements, while the other includes using the perspective property on the parent element residing over child elements being transformed.

Using the perspective value within the transform property works great for transforming one element from a single, unique perspective. When you want to transform a group of elements all with the same perspective, or vanishing point, apply the perspective property to their parent element.

The example below shows a handful of elements all transformed using their individual perspectives with the perspective value.

HTML
1 2 3 4<figure class="box">Box 1</figure> <figure class="box">Box 2</figure> <figure class="box">Box 3</figure>               
CSS
1 2 3 4.box {  transform: perspective(200px) rotateX(45deg); }               

Perspective Value Demo

The following example shows a handful of elements, side by side, all transformed using the same perspective, accomplished by using the perspective property on their direct parent element.

HTML
1 2 3 4 5 6<div class="group">  <figure class="box">Box 1</figure>  <figure class="box">Box 2</figure>  <figure class="box">Box 3</figure> </div>               
CSS
1 2 3 4 5 6 7.group {  perspective: 200px; } .box {  transform: rotateX(45deg); }               

Perspective Property Demo

Perspective Depth Value

The perspective value can be set as none or a length measurement. The none value turns off any perspective, while the length value will set the depth of the perspective. The higher the value, the further away the perspective appears, thus creating a fairly low intensity perspective and a small three-dimensional change. The lower the value the closer the perspective appears, thus creating a high intensity perspective and a large three-dimensional change.

Imagine yourself standing 10 feet away from a 10 foot cube as compared to standing 1,000 feet away from the same cube. At 10 feet, your distance to the cube is the same as the dimensions of the cube, therefore the perspective shift is much greater than it will be at 1,000 feet, where the dimensions of the cube are only one one-hundredth of your distance to the cube. The same thinking applies to perspective depth values.

HTML
1 2 3<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure>               
CSS
1 2 3 4 5 6 7.box-1 {  transform: perspective(100px) rotateX(45deg); } .box-2 {  transform: perspective(1000px) rotateX(45deg); }               

Perspective Depth Value Demo

Perspective Origin

As with setting a transform-origin you can also set a perspective-origin. The same values used for the transform-origin property may also be used with the perspective-origin property, and maintain the same relationship to the element. The large difference between the two falls where the origin of a transform determines the coordinates used to calculate the change of a transform, while the origin of a perspective identifies the coordinates of the vanishing point of a transform.

HTML
1 2 3 4 5 6 7 8 9 10<div class="original original-1">  <figure class="box">Box 1</figure> </div> <div class="original original-2">  <figure class="box">Box 2</figure> </div> <div class="original original-3">  <figure class="box">Box 3</figure> </div>               
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16.original {  perspective: 200px; } .box {  transform: rotateX(45deg); } .original-1 {  perspective-origin: 0 0; } .original-2 {  perspective-origin: 75% 75%; } .original-3 {  perspective-origin: 20px 40px; }               

Perspective Origin Demo

3D Transforms

Working with two-dimensional transforms we are able to alter elements on the horizontal and vertical axes, however there is another axis along which we can transform elements. Using three-dimensional transforms we can change elements on the z axis, giving us control of depth as well as length and width.

3D Rotate

So far we’ve discussed how to rotate an object either clockwise or counterclockwise on a flat plane. With three-dimensional transforms we can rotate an element around any axes. To do so, we use three new transform values, including rotateX, rotateY, and rotateZ.

Using the rotateX value allows you to rotate an element around the x axis, as if it were being bent in half horizontally. Using the rotateY value allows you to rotate an element around the y axis, as if it were being bent in half vertically. Lastly, using the rotateZ value allows an element to be rotated around the z axis.

As with the general rotate value before, positive values will rotate the element around its dedicated axis clockwise, while negative values will rotate the element counterclockwise.

HTML
1 2 3 4<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure> <figure class="box-3">Box 3</figure>               
CSS
1 2 3 4 5 6 7 8 9 10.box-1 {  transform: perspective(200px) rotateX(45deg); } .box-2 {  transform: perspective(200px) rotateY(45deg); } .box-3 {  transform: perspective(200px) rotateZ(45deg); }               

3D Rotate Demo

3D Scale

By using the scaleZ three-dimensional transform elements may be scaled on the z axis. This isn’t extremely exciting when no other three-dimensional transforms are in place, as there is nothing in particular to scale. In the demonstration below the elements are being scaled up and down on the z axis, however the rotateX value is added in order to see the behavior of the scaleZ value. When removing the rotateX in this case, the elements will appear to be unchanged.

HTML
1 2 3<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure>               
CSS
1 2 3 4 5 6 7.box-1 {  transform: perspective(200px) scaleZ(1.75) rotateX(45deg); } .box-2 {  transform: perspective(200px) scaleZ(.25) rotateX(45deg); }               

3D Scale Demo

3D Translate

Elements may also be translated on the z axis using the translateZ value. A negative value here will push an element further away on the z axis, resulting in a smaller element. Using a positive value will pull an element closer on the z axis, resulting in a larger element.

While this may appear to be very similar to that of the two-dimensional transform scale value, it is actually quite different. The transform is taking place on the z axis, not the x or y axes. When working with three-dimensional transforms, being able to move an element on the z axis does have great benefits, like when building the cube below for example.

HTML
1 2 3<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure>               
CSS
1 2 3 4 5 6 7.box-1 {  transform: perspective(200px) translateZ(-50px); } .box-2 {  transform: perspective(200px) translateZ(50px); }               

3D Translate Demo

3D Skew

Skew is the one two-dimensional transform that cannot be transformed on a three-dimensional scale. Elements may be skewed on the x and y axis, then transformed three-dimensionally as wished, but they cannot be skewed on the z axis.

Shorthand 3D Transforms

As with combining two-dimensional transforms, there are also properties to write out shorthand three-dimensional transforms. These properties include rotate3d, scale3d, transition3d, and matrix3d. These properties do require a bit more math, as well as a strong understanding of the matrices behind each transform. Should you be interested in looking a bit deeper into them, please do!

Transform Style

On occasion three-dimensional transforms will be applied on an element that is nested within a parent element which is also being transformed. In this event, the nested, transformed elements will not appear in their own three-dimensional space. To allow nested elements to transform in their own three-dimensional plane use the transform-style property with the preserve-3d value.

The transform-style property needs to be placed on the parent element, above any nested transforms. The preserve-3d value allows the transformed children elements to appear in their own three-dimensional plane while the flat value forces the transformed children elements to lie flat on the two-dimensional plane.

HTML
1 2 3 4 5 6 7<div class="rotate three-d">  <figure class="box">Box 1</figure> </div> <div class="rotate">  <figure class="box">Box 2</figure> </div>               
CSS
1 2 3 4 5 6 7 8 9 10 11.rotate {  transform: perspective(200px) rotateY(45deg); } .three-d {  transform-style: preserve-3d; } .box {  transform: rotateX(15deg) translateZ(20px);  transform-origin: 0 0; }               

Transform Style Demo

To see an additional example of the transform-style property in action check out the WebKit explanation.

Backface Visibility

When working with three-dimensional transforms, elements will occasionally be transformed in a way that causes them to face away from the screen. This may be caused by setting the rotateY(180deg) value for example. By default these elements are shown from the back. So if you prefer not to see these elements at all, set the backface-visibility property to hidden, and you will hide the element whenever it is facing away from the screen.

The other value to backface-visibility is visible which is the default value, always displaying an element, no matter which direction it faces.

In the demonstration below notice how the second box isn’t displayed because backface-visibility: hidden; declaration has been set. The backface-visibility property takes even more significance when using animations.

HTML
1 2 3<figure class="box-1">Box 1</figure> <figure class="box-2">Box 2</figure>               
CSS
1 2 3 4 5 6 7 8.box-1 {  transform: rotateY(180deg); } .box-2 {  backface-visibility: hidden;  transform: rotateY(180deg); }               

Backface Visibility Demo

3D Cube Demo

HTML

1 2 3 4 5 6 7 8 9 10 11

1
2
3
4
5
6

CSS

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39.cube-container { height: 200px; perspective: 300; position: relative; width: 200px; } .cube { height: 100%; position: absolute; transform: translateZ(-100px); transform-style: preserve-3d; width: 100%; } .side { background: rgba(45, 179, 74, .3); border: 2px solid #2db34a; height: 196px; position: absolute; width: 196px; } .front { transform: translateZ(100px); } .back { transform: rotateX(180deg) translateZ(100px); } .left { transform: rotateY(-90deg) translateZ(100px); } .right { transform: rotateY(90deg) translateZ(100px); } .top { transform: rotateX(90deg) translateZ(100px); } .bottom { transform: rotateX(-90deg) translateZ(100px); }

Demo


Transitions & Animations

https://learn.shayhowe.com/advanced-html-css/transitions-animations/

One evolution with CSS3 was the ability to write behaviors for transitions and animations. Front end developers have been asking for the ability to design these interactions within HTML and CSS, without the use of JavaScript or Flash, for years. Now their wish has come true.

With CSS3 transitions you have the potential to alter the appearance and behavior of an element whenever a state change occurs, such as when it is hovered over, focused on, active, or targeted.

Animations within CSS3 allow the appearance and behavior of an element to be altered in multiple keyframes. Transitions provide a change from one state to another, while animations can set multiple points of transition upon different keyframes.

Transitions

As mentioned, for a transition to take place, an element must have a change in state, and different styles must be identified for each state. The easiest way for determining styles for different states is by using the :hover, :focus, :active, and :target pseudo-classes.

There are four transition related properties in total, including transition-property, transition-duration, transition-timing-function, and transition-delay. Not all of these are required to build a transition, with the first three are the most popular.

In the example below the box will change its background color over the course of 1 second in a linear fashion.

1 2 3 4 5 6 7 8 9 10.box {  background: #2db34a;  transition-property: background;  transition-duration: 1s;  transition-timing-function: linear; } .box:hover {  background: #ff7b29; }               

Transition Demo

Vendor Prefixes

The code above, as with the rest of the code samples in this lesson, are not vendor prefixed. This is intentionally un-prefixed in the interest of keeping the code snippet small and comprehensible. For the best support across all browsers, use vendor prefixes.

For reference, the prefixed version of the code above would look like the following.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19.box {    background: #2db34a;    -webkit-transition-property: background;       -moz-transition-property: background;         -o-transition-property: background;            transition-property: background;    -webkit-transition-duration: 1s;       -moz-transition-duration: 1s;         -o-transition-duration: 1s;            transition-duration: 1s;    -webkit-transition-timing-function: linear;       -moz-transition-timing-function: linear;         -o-transition-timing-function: linear;            transition-timing-function: linear; } .box:hover {  background: #ff7b29; }                 

Transitional Property

The transition-property property determines exactly what properties will be altered in conjunction with the other transitional properties. By default, all of the properties within an element’s different states will be altered upon change. However, only the properties identified within the transition-property value will be affected by any transitions.

In the example above, the background property is identified in the transition-property value. Here the background property is the only property that will change over the duration of 1 second in a linear fashion. Any other properties included when changing an element’s state, but not included within the transition-property value, will not receive the transition behaviors as set by the transition-duration or transition-timing-function properties.

If multiple properties need to be transitioned they may be comma separated within the transition-property value. Additionally, the keyword value all may be used to transition all properties of an element.

1 2 3 4 5 6 7 8 9 10 11 12.box {    background: #2db34a;    border-radius: 6px    transition-property: background, border-radius;    transition-duration: 1s;    transition-timing-function: linear;  }  .box:hover {    background: #ff7b29;    border-radius: 50%;  }               

Transition Property Demo

Transitional Properties

It is important to note, not all properties may be transitioned, only properties that have an identifiable halfway point. Colors, font sizes, and the alike may be transitioned from one value to another as they have recognizable values in-between one another. The display property, for example, may not be transitioned as it does not have any midpoint. A handful of the more popular transitional properties include the following.

  • background-color
  • background-position
  • border-color
  • border-width
  • border-spacing
  • bottom
  • clip
  • color
  • crop
  • font-size
  • font-weight
  • height
  • left
  • letter-spacing
  • line-height
  • margin
  • max-height
  • max-width
  • min-height
  • min-width
  • opacity
  • outline-color
  • outline-offset
  • outline-width
  • padding
  • right
  • text-indent
  • text-shadow
  • top
  • vertical-align
  • visibility
  • width
  • word-spacing
  • z-index

Transition Duration

The duration in which a transition takes place is set using the transition-duration property. The value of this property can be set using general timing values, including seconds (s) and milliseconds (ms). These timing values may also come in fractional measurements, .2s for example.

When transitioning multiple properties you can set multiple durations, one for each property. As with the transition-property property value, multiple durations can be declared using comma separated values. The order of these values when identifying individual properties and durations does matter. For example, the first property identified within the transition-property property will match up with the first time identified within the transition-duration property, and so forth.

If multiple properties are being transitioned with only one duration value declared, that one value will be the duration of all the transitioned properties.

1 2 3 4 5 6 7 8 9 10 11 12.box {  background: #2db34a;  border-radius: 6px;  transition-property: background, border-radius;  transition-duration: .2s, 1s;  transition-timing-function: linear; } .box:hover {  background: #ff7b29;  border-radius: 50%; }               

Transition Duration Demo

Transition Timing

The transition-timing-function property is used to set the speed in which a transition will move. Knowing the duration from the transition-duration property a transition can have multiple speeds within a single duration. A few of the more popular keyword values for the transition-timing-function property include linear, ease-in, ease-out, and ease-in-out.

The linear keyword value identifies a transition moving in a constant speed from one state to another. The ease-in value identifies a transition that starts slowly and speeds up throughout the transition, while the ease-out value identifies a transition that starts quickly and slows down throughout the transition. The ease-in-out value identifies a transition that starts slowly, speeds up in the middle, then slows down again before ending.

Each timing function has a cubic-bezier curve behind it, which can be specifically set using the cubic-bezier(x1, y1, x2, y2) value. Additional values include step-start, step-stop, and a uniquely identified steps(number_of_steps, direction) value.

When transitioning multiple properties, you can identify multiple timing functions. These timing function values, as with other transition property values, may be declared as comma separated values.

1 2 3 4 5 6 7 8 9 10 11 12.box {  background: #2db34a;  border-radius: 6px;  transition-property: background, border-radius;  transition-duration: .2s, 1s;  transition-timing-function: linear, ease-in; } .box:hover {  background: #ff7b29;  border-radius: 50%; }               

Transition Timing Demo

Transition Delay

On top of declaring the transition property, duration, and timing function, you can also set a delay with the transition-delay property. The delay sets a time value, seconds or milliseconds, that determines how long a transition should be stalled before executing. As with all other transition properties, to delay numerous transitions, each delay can be declared as comma separated values.

1 2 3 4 5 6 7 8 9 10 11 12 13.box {  background: #2db34a;  border-radius: 6px  transition-property: background, border-radius;  transition-duration: .2s, 1s;  transition-timing-function: linear, ease-in;  transition-delay: 0s, 1s; } .box:hover {  background: #ff7b29;  border-radius: 50%; }               

Transition Delay Demo

Shorthand Transitions

Declaring every transition property individually can become quite intensive, especially with vendor prefixes. Fortunately there is a shorthand property, transition, capable of supporting all of these different properties and values. Using the transition value alone, you can set every transition value in the order of transition-property, transition-duration, transition-timing-function, and lastly transition-delay. Do not use commas with these values unless you are identifying numerous transitions.

To set numerous transitions at once, set each individual group of transition values, then use a comma to separate each additional group of transition values.

1 2 3 4 5 6 7 8 9 10.box {  background: #2db34a;  border-radius: 6px;  transition: background .2s linear, border-radius 1s ease-in 1s; } .box:hover {  color: #ff7b29;  border-radius: 50%; }               

Shorthand Transitions Demo

Transitional Button

HTML
1 2<button>Awesome Button</button>                 
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18button {  border: 0;  background: #0087cc;  border-radius: 4px;  box-shadow: 0 5px 0 #006599;  color: #fff;  cursor: pointer;  font: inherit;  margin: 0;  outline: 0;  padding: 12px 20px;  transition: all .1s linear; } button:active {  box-shadow: 0 2px 0 #006599;  transform: translateY(3px); }                 

Demo

Card Flip

HTML
1 2 3 4 5 6 7<div class="card-container">  <div class="card">    <div class="side">...</div>    <div class="side back">...</div>  </div> </div>                 
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26.card-container {  height: 150px;  perspective: 600;  position: relative;  width: 150px; } .card {  height: 100%;  position: absolute;  transform-style: preserve-3d;  transition: all 1s ease-in-out;  width: 100%; } .card:hover {  transform: rotateY(180deg); } .card .side {  backface-visibility: hidden;  height: 100%;  position: absolute;  width: 100%; } .card .back {  transform: rotateY(180deg); }                 

Demo

Animations

Transitions do a great job of building out visual interactions from one state to another, and are perfect for these kinds of single state changes. However, when more control is required, transitions need to have multiple states. In return, this is where animations pick up where transitions leave off.

Animations Keyframes

To set multiple points at which an element should undergo a transition, use the @keyframes rule. The @keyframes rule includes the animation name, any animation breakpoints, and the properties intended to be animated.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15@keyframes slide {  0% {    left: 0;    top: 0;  }  50% {    left: 244px;    top: 100px;  }  100% {    left: 488px;    top: 0;  } }               

Vendor Prefixing the Keyframe Rule

The @keyframes rule must be vendor prefixed, just like all of the other transition and animation properties. The vendor prefixes for the @keyframes rule look like the following:

  • @-moz-keyframes
  • @-o-keyframes
  • @-webkit-keyframes

The animation above is named slide, stated directly after the opening @keyframes rule. The different keyframe breakpoints are set using percentages, starting at 0% and working to 100% with an intermediate breakpoint at 50%. The keywords from and to could be used in place of 0% and 100% if wished. Additional breakpoints, besides 50%, may also be stated. The element properties to be animated are listed inside each of the breakpoints, left and top in the example above.

It is important to note, as with transitions only individual properties may be animated. Consider how you might move an element from top to bottom for example. Trying to animate from top: 0; to bottom: 0; will not work, because animations can only apply a transition within a single property, not from one property to another. In this case, the element will need to be animated from top: 0; to top: 100%;.

Animations Keyframes Demo

Hover over the ball below to see the animation in action.

Animation Name

Once the keyframes for an animation have been declared they need to be assigned to an element. To do so, the animation-name property is used with the animation name, identified from the @keyframes rule, as the property value. The animation-name declaration is applied to the element in which the animation is to be applied to.

1 2 3 4.stage:hover .ball {  animation-name: slide; }               

Using the animation-name property alone isn’t enough though. You also need to declare an animation-duration property and value so that the browser knows how long an animation should take to complete.

Animation Duration, Timing Function, & Delay

Once you have declared the animation-name property on an element, animations behave similarly to transitions. They include a duration, timing function, and delay if desired. To start, animations need a duration declared using the animation-duration property. As with transitions, the duration may be set in seconds or milliseconds.

1 2 3 4 5.stage:hover .ball {  animation-name: slide;  animation-duration: 2s; }               

A timing function and delay can be declared using the animation-timing-function and animation-delay properties respectively. The values for these properties mimic and behave just as they do with transitions.

1 2 3 4 5 6 7.stage:hover .ball {  animation-name: slide;  animation-duration: 2s;  animation-timing-function: ease-in-out;  animation-delay: .5s; }               

The animation below should cause the ball to bounce once while moving to the left, however only when hovering over the stage.

HTML
1 2 3 4<div class="stage">  <figure class="ball"></figure> </div>               
CSS
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30@keyframes slide {  0% {    left: 0;    top: 0;  }  50% {    left: 244px;    top: 100px;  }  100% {    left: 488px;    top: 0;  } } .stage {  height: 150px;  position: relative; } .ball {    height: 50px;    position: absolute;    width: 50px; } .stage:hover .ball {  animation-name: slide;  animation-duration: 2s;  animation-timing-function: ease-in-out;  animation-delay: .5s; }               

Animation Demo

Hover over the ball below to see the animation in action.

Customizing Animations

Animations also provide the ability to further customize an element’s behavior, including the ability to declare the number of times an animation runs, as well as the direction in which an animation completes.

Animation Iteration

By default, animations run their cycle once from beginning to end and then stop. To have an animation repeat itself numerous times the animation-iteration-count property may be used. Values for the animation-iteration-count property include either an integer or the infinite keyword. Using an integer will repeat the animation as many times as specified, while the infinite keyword will repeat the animation indefinitely in a never ending fashion.

1 2 3 4 5 6 7 8.stage:hover .ball {  animation-name: slide;  animation-duration: 2s;  animation-timing-function: ease-in-out;  animation-delay: .5s;  animation-iteration-count: infinite; }               

Animation Iteration Demo

Hover over the ball below to see the animation in action.

Animation Direction

On top of being able to set the number of times an animation repeats, you may also declare the direction an animation completes using the animation-direction property. Values for the animation-direction property include normal, reverse, alternate, and alternate-reverse.

The normal value plays an animation as intended from beginning to end. The reverse value will play the animation exactly opposite as identified within the @keyframes rule, thus starting at 100% and working backwards to 0%.

The alternate value will play an animation forwards then backwards. Within the keyframes that includes running forward from 0% to 100% and then backwards from 100% to 0%. Using the animation-iteration-count property may limit the number of times an animation runs both forwards and backwards. The count starts at 1 running an animation forwards from 0% to 100%, then adds 1 running an animation backwards from 100% to 0%. Combining for a total of 2 iterations. The alternate value also inverses any timing functions when playing in reverse. If an animation uses the ease-in value going from 0% to 100%, it then uses the ease-out value going from 100% to 0%.

Lastly, the alternate-reverse value combines both the alternate and reverse values, running an animation backwards then forwards. The alternate-reverse value starts at 100% running to 0% and then back to 100% again.

1 2 3 4 5 6 7 8 9.stage:hover .ball {  animation-name: slide;  animation-duration: 2s;  animation-timing-function: ease-in-out;  animation-delay: .5s;  animation-iteration-count: infinite;  animation-direction: alternate; }               

Animation Direction Demo

Hover over the ball below to see the animation in action.

Animation Play State

The animation-play-state property allows an animation to be played or paused using the running and paused keyword values respectively. When you play a paused animation, it will resume running from its current state rather than starting from the very beginning again.

In the example below the animation-play-state property is set to paused when making the stage active by clicking on it. Notice how the animation will temporarily pause until you let up on the mouse.

1 2 3 4 5 6 7 8 9 10 11 12.stage:hover .ball {  animation-name: slide;  animation-duration: 2s;  animation-timing-function: ease-in-out;  animation-delay: .5s;  animation-iteration-count: infinite;  animation-direction: alternate; } .stage:active .ball {  animation-play-state: paused; }               

Animation Play State Demo

Hover over the ball below to see the animation in action. Click to pause the animation.

Animation Fill Mode

The animation-fill-mode property identifies how an element should be styled either before, after, or before and after an animation is run. The animation-fill-mode property accepts four keyword values, including none, forwards, backwards, and both.

The none value will not apply any styles to an element before or after an animation has been run.

The forwards value will keep the styles declared within the last specified keyframe. These styles may, however, be affected by the animation-direction and animation-iteration-count property values, changing exactly where an animation ends.

The backwards value will apply the styles within the first specified keyframe as soon as being identified, before the animation has been run. This does include applying those styles during any time that may be set within an animation delay. The backwards value may also be affected by the animation-direction property value.

Lastly, the both value will apply the behaviors from both the forwards and backwards values.

1 2 3 4 5 6 7 8 9 10 11.stage:hover .ball {  animation-name: slide;  animation-duration: 2s;  animation-timing-function: ease-in-out;  animation-delay: .5s;  animation-fill-mode: forwards; } .stage:active .ball {  animation-play-state: paused; }               

Animation Fill Mode Demo

Hover over the ball below to see the animation in action. Click to pause the animation.

Shorthand Animations

Fortunately animations, just like transitions, can be written out in a shorthand format. This is accomplished with one animation property, rather than multiple declarations. The order of values within the animation property should be animation-name, animation-duration, animation-timing-function, animation-delay, animation-iteration-count, animation-direction, animation-fill-mode, and lastly animation-play-state.

1 2 3 4 5 6 7.stage:hover .ball {  animation: slide 2s ease-in-out .5s infinite alternate; } .stage:active .ball {  animation-play-state: paused; }               

Shorthand Animations Demo

Hover over the ball below to see the animation in action. Click to pause the animation.


Feature Support & Polyfills

https://learn.shayhowe.com/advanced-html-css/feature-support-polyfills/

Building a website can be both extremely rewarding and frustrating. Common frustrations arise from trying to get a website to look and perform the same in every browser. All front end developers have shared this frustration at one point or another.

Truth be told, websites do not need to look or perform the same in every browser. Exactly how close a website works in each browser is up to you and your level of comfort for a given website. If a website receives under half a percent of traffic from Internet Explorer 6 it might make sense to drop support for it. If that half a percent is still contributing to thousands of dollars in sales, support may be mandatory. Determine what is acceptable for a given website and work from there.

There are a handful of common practices to get websites to perform adequately in all browsers, some of which have already been covered within this guide. When incorporating CSS3 properties, fallbacks are recommend to support older browsers. Other techniques include shivs and polyfills. Generally speaking, shivs and polyfills are small JavaScript plugins that add support for a requested set of features not natively supported by a specific browser.

HTML5 Shiv

Perhaps the most popular shiv, and one you may have likely used already, is the HTML5 Shiv. The HTML5 Shiv was created by Remy Sharp to provide the ability to use HTML5 elements within versions of Internet Explorer 8 and below. The HTML5 Shiv not only creates support for HTML5 elements but also allows them to be properly styled with CSS.

The shiv should be downloaded from Google, where Remy maintains the latest version, then hosted on your server. For the best performance, reference the shiv JavaScript file within the head of the document, after any stylesheet references. Additionally, you want to reference the shiv inside of a conditional comment, making sure that the file is only loaded within versions of Internet Explorer 8 and below.

In this case the conditional comment looks like <!--[if lt IE 9]>...<![endif]-->.

1 2 3 4<!--[if lt IE 9]>  <script src="html5shiv.js"></script> <![endif]-->               

The Difference Between a Shiv & a Shim

Chances are you may have heard of both the HTML5 Shiv and HTML5 Shim, and wondered what the difference, if any, may be. Oddly enough, there is no difference between the HTML5 Shiv and HTML5 Shim. The two words are often used interchangeably and are commonly transposed.

Additionally, once the new HTML5 elements are created using the shiv, any block level elements need to be identified and updated using the display: block; declaration.

1 2 3 4 5 6 7 8 9 10 11 12 13 14article, aside, details, figcaption, figure, footer, header, hgroup, nav, section, summary {  display: block; }               

Lastly, Internet Explorer 8 and 9 do not correctly define styles for a few HTML5 inline-block level elements. As before, these styles will need to be explicitly stated. After which, all versions of Internet Explorer should be good to go using any new HTML5 elements.

1 2 3 4 5 6audio, canvas, video {  display: inline-block; }               

Detecting Browser Features

Referencing the HTML5 Shiv works well with a conditional comment because the intention is to specifically target browsers that don’t support new HTML5 features and elements. Additionally, there is a way to to provide support for specific HTML5 and CSS3 features, regardless of which browser is being used.

Feature detection, as provided by Modernizr, provides a way to write conditional CSS and JavaScript based on whether or not a browser supports a specific feature. For example, if a browser supports rounded corners Modernizr will add the class of borderradius to the html element. If the browser doesn’t support rounded corners, Modernizr will add the class of no-borderradius to the html element.

Loading Modernizr

To get feature detection with Modernizr up and running, visit their download page and customize what features you are looking to detect. Once downloaded, upload the JavaScript file on your server and reference it within the head of your HTML document, below any referenced style sheets.

It is worth noting that Modernizr may be configured to include the HTML5 Shiv, in which case the shiv doesn’t need to be referenced on top of Modernizr.

1 2<script src="modernizr.js"></script>               

Conditionally Applying CSS Styles

Once Modernizr is up and running CSS styles may be conditionally applied based on the features a given browser supports. Modernizr has detection for the majority of the CSS3 properties and values, all of which can be found in the Modernizr documentation.

One item to weigh out is if feature detection is necessary for certain styles. For example, using an RGBa color value may easily be supported with a fallback hexadecimal value without the use of feature detection. When deciding to use feature detection, it is important to keep styles organized and performance in mind. Avoid duplicating any code or making additional HTTP requests when possible.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38button {  border: 0;  color: #fff;  cursor: pointer;  font-size: 14px;  font-weight: 600;  margin: 0;  outline: 0; } /* With CSS Gradient Styles */ .cssgradients button {  border: 1px solid #0080c2;  background: linear-gradient(#00a2f5, #0087cc);  border-radius: 6px;  padding: 15px 30px; } .cssgradients button:hover {  background: linear-gradient(#1ab1ff, #009beb); } .cssgradients button:active {  box-shadow: inset 0 1px 10px rgba(255, 255, 255, .5); } /* Without CSS Gradient Styles */ .no-cssgradients button {  background: transparent url("clickety-clack-site/june2021/button.png") 0 0 no-repeat;  padding: 16px 31px; } .no-cssgradients button:hover {  background-position: 0 -49px; } .no-cssgradients button:active {  background-position: 0 -98px; }               

Feature Detection Demo

In the demonstration above, the button inherits some default styles. However, specific styles are only applied based on whether or not CSS3 gradient background are supported. In this case, rounded corners and box shadows are also included within the conditional styles. Those browsers that support gradients get a gradient background, rounded corners, and a box shadow. Those browsers that do not receive an image with all of these styles included within the image. With this code none of the styles are being over written and an HTTP request is only made when necessary.

When working with CSS3 feature detection it is hard to know what the styles look like in browsers that do not support specific CSS3 features. Fortunately, there is a bookmarklet called deCSS3 which disables any CSS3 features. Doing so allows you to see what a website would look like without CSS3, and if your conditional styles are working. To get a quick idea of what an individual browser supports, visit haz.io within that specific browser.

Conditionally Loading Files

On top of conditionally loading styles, Modernizr also provides a way to use feature detection in JavaScript. With this, JavaScript polyfills and conditional files may be loaded based on the detection of a given feature with the help of jQuery and the jQuery getScript method.

Using Modernizr to set the condition of an if statement in Javascript allows different scripts to be executed based on whether or not the given condition is true or false. Below Modernizr is checking for local storage support. If local storage is supported jQuery is used to load the storage.js file using the getScript method, and if local storage is not supported jQuery is used the storage-polyfill.js file using the getScript method.

1 2 3 4 5 6 7 8 9 10$(document).ready(function() {  if (Modernizr.localstorage) {    // Local storage is available    jQuery.getScript('storage.js');  } else {    // Local storage is not available    jQuery.getScript('storage-polyfill.js');  } });               

Conditionally Loading Based on Media Queries

One interesting condition Modernizr can test against is media queries. Doing so provides the ability to only load files based on different media query conditions. Not loading unnecessary files can be extremely beneficial for performance.

1 2 3 4 5 6$(document).ready(function() {  if (Modernizr.mq('screen and (min-width: 640px)')) {    jQuery.getScript('tabs.js');  } });               

Above, Modernizr looks to detect screens above 640 pixels wide, primarily desktops, and then loads the tabs.js file based off of this condition. It is important to note that this condition is tested only once, when the page loads, and that is it. Should a user resize the page, this condition will not be retested. Should this condition need to be retested, additional JavaScript would need to be included.

Conditionally Running Scripts

Using Modernizr, all of the HTML5 and CSS3 features they detect may be tested within JavaScript. For example, it may be worth disabling tooltips on mobile devices due to not having hover capabilities, and instead showing the tooltip in plain text on the screen. The script for calling these tooltips could be wrapped in a Modernizr condition, preventing the script from loading on smaller screens.

1 2 3 4 5 6$(document).ready(function() {  if (Modernizr.mq('screen and (max-width: 400px)')) {    $('.size').text('small');  } });               

Conditionally Running Scripts Demo

Above is a basic example of how JavaScript can be executed based on a condition established by Modernizr. Upon loading the page, if the screen is above 800 pixels wide nothing happens. However, if the screen is below 800 pixels wide, upon being loaded, the word ‘small’ will be swapped for ‘large’ based off of the executed JavaScript.

HTML5 & CSS3 Polyfills

Currently there are polyfills for nearly all of the different HTML5 and CSS3 features. The team over at Modernizr has put together quite an exhaustive list of polyfills. These polyfills can be dropped in as needed.

The same people behind Modernizr have also put together a list of all of the new HTML5 and CSS3 features, including instructions on how to use them responsibly. Understand, not all of these features need polyfills. Quite a few of them can be used outright or with the use of a fallback.

Cross Browser Testing

Perhaps the most dreaded part of web design and development is cross browser testing, making sure a website works well in all browsers. Generally speaking the more modern browsers, Chrome, Firefox, and Safari, all perform pretty well. The largest pitfalls live within Internet Explorer, and testing different versions of Internet Explorer can be difficult.

There are a handful of services out there that do help with cross browser testing, some are interactive while others are not. Being able to interact with a browser, rather than seeing a rendered screenshot, is far more helpful for debugging code. One of the best ways to boot up multiple versions of Internet Explorer is by using multiple virtual machines, each with a different version of Internet Explorer.

VirtualBox

Fig. 9

VirtualBox running on Mac OS X with Internet Explorer versions 6 through 9.

Microsoft provides a handful of VirtualPCs that can be used solely for testing. Setting all of these up can be a herculean task. Fortunately, Greg Thornton has built an automated installer for all of these virtual machines. The installation takes a while to download all of the different virtual machines, and requires a decent amount of disk space. Prepare adequately by only installing the necessary virtual machines and by clearing up the necessary disk space ahead of time. Depending on how often the virtual machines are used, it may be worth installing them on an external hard drive.

Internet Explorer versions 8 and above have built-in development tools, unfortunately versions 7 and below do not. The web inspector and all of the other debugging tools we’ve grown to love are not readily available within Internet Explorer 7 and below. There is, however, a Firebug Lite bookmarklet that provides an in browser inspector that is tremendously helpful.

VirtualBox

Fig. 9

Internet Explorer 7 running inside of a virtual machine with the Firebug Lite bookmarklet open for debugging.


Extending Semantics & Accessibility

https://learn.shayhowe.com/advanced-html-css/semantics-accessibility/

Semantics and accessibility are naturally part of HTML by design, however they are not fully leveraged unless used accordingly. Knowing how to write semantic and accessible code properly takes an understanding of how semantics and accessibility work, and how users and machines interpret them. Writing semantic and accessible code isn’t incredibly difficult, but it can be time consuming. In the long run, however, the benefits win out.

One of the more important parts to remember when writing semantic and accessible code is to do your best to leverage the standard markup language. Do your best to write the cleanest code possible, and take pride in your work. Generally speaking, don’t use a meaningless element where another element might make more semantic sense, using a div where a h2 would be better fitted for example. Use semantic elements and attributes, as well as microdata and WAI-ARIA to extend the value of your code.

Additionally, be an advocate for semantics and accessibility. Tell others why you’ve written certain code, and provide reasoning why certain modules of content are marked up in a specific way. Outline goals and objectives within your code, and explain how those goals and objectives are being accomplished. The practice of writing semantic and accessible code is growing, however adoption at large has not yet been achieved. Be an advocate for the code you write.

Semantic Motivation

Occasionally, one may ask if semantics really make a difference. You may hear they slow down development, are poorly supported, or that they are even opinionated. While this may have some validity, you still need to retain integrity and continue to write the best code possible, for semantics provide a larger meaning in writing code.

The fact of the matter is, semantics largely benefit everyone. For starters, semantics provide a shared and unambiguous meaning to content. Semantics give content solid structure and value, while also favoring accessibility, providing better user interfaces and more defined information to assistive technologies. Search and globalization is more permanent with semantics, making it easier to serve content internationally and making it more search engine friendly. Should that not be enough, semantics also promote interoperability, allowing the exchange and use of information across different platforms and devices.

It’s safe to say semantics are important, and here to stay. To briefly recap, semantics provide:

  • Unambiguous, shared meaning within content
  • Accessibility
  • Search and globalization
  • Interoperability

Structural Semantics

Within the beginner’s guide we discuss the use of structural semantics, specifically using the header, nav, article, section, aside, and footer elements. These elements are used to provide additional background context to the content within them, communicating their core meaning to web browsers and other devices. This is important, as it provides a better way to outline and structure pages, not to mention a more meaningful solution than divisions.

Hiding Content

Every now and then you may want to hide a block of content on the page, perhaps showing or hiding an element depending on a user’s state. For example, having a success message hidden from a user until they complete a desired action. Most commonly, this is accomplished with the display: none; CSS declaration. While this does work, it is semantically incorrect.

A better option is to use the hidden Boolean attribute, which is a global attribute available to all elements for use. Functionally it performs the same way as the CSS declaration, but semantically it represents an element that should be hidden, or ignored, for the time being. Screen readers and other devices will recognize this, temporarily skipping it, where they may not done so with the CSS declaration.

1 2 3 4 5 6<!-- Good --> <div hidden>...</div> <!-- Not good --> <div style="display: none;">...</div>               

Imagine a blind user attempting to fill out a form and the first piece of content, before even filling out the form, is a success message. This is a poor user experience, and one that can easily be fixed using proper semantics.

Text Level Semantics

The majority of content on the web lives within text, and we primarily browse the Internet looking for this content. Using the proper semantic markup for text makes it easier for users to find what they need.

Bolding Text

There are a few different ways to make text bold, including multiple elements and the font weight CSS property. The two main elements used in this case include strong and b. While these two elements have the same presentation they have completely different semantic meanings.

The strong element outlines text that has a strong importance. On the contrasting side, the b element identifies text that is to be stylistically offset, without importance. Generally speaking, the b element should be used solely as a styling hook to change the presentation of an element, where the strong element should be used to identify significantly important text.

1 2 3 4 5 6<!-- Strong importance --> <strong>Caution:</strong> Falling rocks. <!-- Stylistically offset --> This recipe calls for <b>bacon</b> and <b>baconnaise</b>.               

Bolding Text Demo

Italicizing Text

Italicizing text falls in line with that of bolding text, where we can use multiple elements or the font style CSS property to achieve a desired presentation. When italicizing text, the two elements most commonly used are em and i. Again, these share the same presentation, yet have completely different semantic meanings.

The em element places a stressed emphasis on text, while the i element identifies text to be expressed in an alternate voice or tone. Using the em element really drives prominence with an added importance. On the other hand, the i element is primarily used within dialog or prose, offsetting text without any added emphasis or importance.

1 2 3 4 5 6<!-- Stressed emphasis --> I <em>love</em> Chicago! <!-- Alternative voice or tone --> The name <i>Shay</i> means a gift.               

Italicizing Text Demo

Using i for Icons

Recently there has been a small movement of front end programmers using the i element for including icons on a page, specifically as seen within Bootstrap. The i element is used as a hook, to which a class then determines which icon background image to apply to the element. Depending on how closely you wish to follow semantics this may or may not be an acceptable practices.

Underlining Text

Continuing the pattern of having multiple elements with the same presentation, underlining text is no different. There are a couple of different elements we can use as well as the text decoration CSS property. In this case, the two primary elements used to underline text are ins and u.

The ins element is used to identify text that has been recently added to the document, and the u element simply refers to an unarticulated annotation.

For more semantic code, the ins element may be used with the cite and datetime attributes. The datetime attribute identifies when the content was added to the document, and the cite attribute provides a machine readable source providing reference for the addition, perhaps documentation or a request ticket.

The u element is typically used to label text as a proper name, often in another language, or to point out a misspelling.

Underlining text does require a bit of additional care, as it may be confused with a hyperlink. By default hyperlinks are underlined, and thus have become a standard design practice. Underlining text that is not a hyperlink can confuse users and cause quite a bit of frustration. Use underlines with caution.

1 2 3 4 5 6 7 8<!-- Added to the document --> <ins cite="http://learn.shayhowe.com" datetime="2012-07-01">  Updated: This website now contains an advanced guide. </ins> <!-- Unarticulated annotation --> <u>Urushihara Yuuji</u> won <u>Sasuke 27</u>.               

Underlining Text Demo

Striking Text

Striking text follows the same pattern as before where different elements may be used, as may the text decoration CSS property. The two properties most commonly used include del and s.

The del element is used to identify text deleted or removed from the document. As with the ins element, it may be used with the cite and datetime attributes. Each of which hold the identical semantic values as before, cite specifying a resource that explains the change and datetime identifying when the content was removed from the document.

The s element identifies text that is no longer accurate or relevant.

1 2 3 4 5 6<!-- Deleted from the document --> I am an avid cyclist, <del cite="http://shayhowe.com" datetime="2012-07-01">skateboarder</del> and designer. <!-- No longer accurate or relevant --> <s>$24.99</s> $19.99               

Striking Text Demo

Highlighting Text

To highlight text for reference purposes the mark element should be used. Added in HTML5, the mark element provides a clean, semantic way to identify text, specifically for reference purposes without having to use an un-semantic text level element.

1 2 3<!-- Highlighted for reference purposes --> Search results for <mark>'chicago'</mark>.               

Highlighting Text Demo

Abbreviations

Abbreviations, the shortened form of a phrase, can be semantically marked up in HTML using the abbr element. The abbr element should be used along with the title attribute, of which includes the full value of the phrase being abbreviated. The acronym element was originally used to distinguish acronyms from abbreviations but has since been deprecated, and shouldn’t be used.

1 2 3<abbr title="HyperText Markup Language">HTML</abbr> <abbr title="Cascading Style Sheets">CSS</abbr>               

Abbreviations Demo

Sub & Superscripts

Subscripts and superscripts may be marked up accordingly using the sub and sup elements respectively. It is important to note that these elements should be reserved for typographical conventions, not for presentational purposes.

1 2 3 4 5 6<!-- Subscript --> H<sub>2</sub>O <!-- Superscripts --> 1<sup>st</sup> Place               

Sub & Superscripts Demo

Meter & Progress

To gauge scale or indicate progress the meter and progress elements should be used. The meter element is used to measure a fixed value, one that does not change over time, while the progress element measures the progress of a increasing measurement.

The meter element may be used with the min, max, low, high, optimum, and value attributes. The min and max attributes set the lower and upper bounds of the range, where the value attribute sets the exact measured value. The low and high attributes identify what is to be considered the lower and higher parts of the range, while the optimum value identifies the most favorable part of the range, of which may be in the lower or higher parts.

The progress element indicates progress rather than a fixed measurement. It specifically represents the completion of a task, either by what is left to be completed or what has been completed thus far. There are two attributes that may be applied to the progress element, value and max. The value attributes indicates where the progress currently stands and the max attribute indicates what progress needs to be reached.

1 2 3 4 5 6 7 8<!-- Meter --> <meter value="7" max="10">7 stars</meter> <meter value="47" min="0" max="105" low="5" high="65" optimum="45">The car is moving at a decent average mile per hour.</meter> <!-- Progress --> You are <progress value="50" max="100">50%</progress> complete. <progress value="50" min="0" max="100">Hold tight, you’re getting there.</progress>               

Meter & Progress Demo

Time & Address

Representing time and addresses in HTML can be accomplished using the time and address elements respectively. The time element may be used with, or without, the datetime attribute, depending on how the text within the element is formatted. If the content is formatted with the correct time stamp then the datetime attribute may be omitted. Furthermore, if the time is representing the date or time of a publication the pubdate Boolean attribute should be used.

The address element may be used to hold any contact information, including a physical address as well as a website or email address. It should not include any further information than the contact information, and other content needs to be placed outside of the address element.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

600 W. Chicago Ave.
Suite 620
Chicago, IL 60654
USA

Time & Address Demo

Presenting Code

Presenting code snippets, or samples, within a page can be accomplished using either the code or pre elements, or a combination of the two. The code element is commonly used to represent a fragment of code and is displayed in the default monospace font. The code element is an inline level element and may be used within paragraphs of text, or other block and inline level elements.

For large blocks of code, the pre element can be used in conjunction with the code element. The pre element represent preformatted text and will display text exactly as it is typed, whitespace included. Nesting the code element within the pre element semantically identifies larger samples of code, which include whitepsace, displayed in a block level manner.

1 2 3 4 5 6 7 8 9<!-- Inline code samples --> Use the <code>article</code> element. <!-- Larger, block level code snippets --> <pre><code>body { color: #666; font: 14px/20px Arial, sans-serif; }</code></pre>

Presenting Code Demo

Line & Word Breaks

Occasionally you may want to include a line break within a line of text, in which case the br element may be used. The br element does not have a closing tag, simply a beginning. In XHTML the br element is self closing, including a trailing forward slash, <br />.

Line breaks are not to be used for thematic grouping of content. Paragraphs or other elements are better suited for thematic grouping. Line breaks are specifically to be used where line breaks exist as part of the content, for example as within addresses and poems.

In addition to line breaks, you may also specify word breaking opportunities with the wbr element. Using the wbr element in the middle of a word ensures that, should the word need to wrap two lines, it does in a legible fashion.

1 2 3 4 5 6 7 8<!-- Line break --> 600 W. Chicago Ave.<br> Chicago, IL 60654<br> USA <!-- Word break --> http://shay<wbr>howe.com

Line & Word Breaks Demo

Side Comments

Originally the small element was used to render text as one font size smaller than the default, purely for presentational purposes. As we are aware, presentation and style should only live within CSS, not HTML. Within HTML5, the small element preserves the presentation of being displayed at a smaller font size, however it semantically means to be rendered as a side comments or small print. This often includes copyright information or legal print.

1 2 3<!-- Side comments or small print --> <small>© 2012 Shay Howe</small>

Side Comments Demo

Citations & Quotes

The beginner’s guide discusses citations and quotes, and when to use the cite, q, and blockquote elements accordingly. As a quick reminder, the cite element refers to a title of work, the q element identifies dialog or prose, and the blockquote element is used to code longer formed quotes, commonly from external sources.

The beginner’s guide also outlines hyperlinks, and some of their different behaviors. What is not covered, however, is some of the semantic benefits to hyperlinks, specifically with the use of the download and rel attributes.

Download Attribute

The download attribute tells the browser to prompt a download for a file, rather than the default behavior of navigation to the file. As an example, if the hyperlink reference attribute, href, is pointing to an image, the browser will prompt a user to download the image instead of opening the image within the browser.

The download attribute can serve as a Boolean attribute, downloading the file as is, or it may contain a value, of which becomes the file name once downloaded. Using a specific value here lets you name the file as you wish on your server while still providing users with a meaningful name.

1 2 3 4 5 6<!-- Boolean --> <a href="twitter-clickety-clack-site/june2021/logo.png" download>Twitter Logo</a> <!-- With a value --> <a href="twitter-clickety-clack-site/june2021/logo.png" download="Logo">Twitter Logo</a>

Download Attribute Demo

Relationship Attribute

For any hyperlinks including a reference attribute, href, you may also include the relationship attribute, rel. The rel attribute identifies the relationship between the current document and the document being referenced. For example, when linking to a copyright statement the rel attribute value of copyright should be used.

1 2 3<a href="legal.html" rel="copyright">Terms of Use</a> <a href="toc.html" rel="contents">Table of Contents</a>

A few popular rel attribute values include:

  • alternate
  • author
  • bookmark
  • help
  • license
  • next
  • nofollow
  • noreferrer
  • prefetch
  • prev
  • search
  • tag

Microdata

Microdata is HTML extended with nested groups of name-value pairs that allow machines, including browsers and search engines, to pick up additional semantics and information for rich content. Adding microdata to your website is accomplished by using predetermined attributes and values. These attributes and values will then be interpreted, and extended, as intended. Currently, the more popular uses of microdata reside within coding contact information and calendar events, however there are encoding models for products, reviews, and more.

One example of microdata at work is within Google, where microdata is interpreted and used within search results to display more relevant data. Often performing a search for a business location yields the address and sub sequential contact information within the results. Chances are this information is being pulled from microdata written on an existing website.

Google Microdata

Fig. 10

Google uses microdata to identify business locations, contact information, hours, pricing, ratings, and more.

Microdata vs. Microformats vs. RDFa

There are actually a handful of rich, structured data standards, including microdata, microformats, and RDFa. All of these have their pros and cons, and all of which are still viable to practice.

Microdata is the recommended format from Google, and other search engines, as well as part of the HTML5 specification. It uses findings from both microformats and RDFa to base it’s design around, thus looking to be a solid choice, and the one covered here. It is, however, recommended you do your research, take the pulse of the community, find what works best for your situation, and use that. Using one of these standards is substantially better than not using any. Find what will provide the best benefit for your users.

Outlining Microdata

Microdata is identified using three main attributes, itemscope, itemtype, and itemprop.

The itemscope Boolean attribute declares the scope of each microdata item. Place this attribute on the parent element where all of the microdata information pertaining to this item should reside.

Once you have determined the scope, use the itemtype attribute to identify what microdata vocabulary should be used. Generally speaking, some of the more popular microdata item types have been outlined at Schema.org. There are, however, other websites which outline additional, and different, item types. You may also write your own item types should you find the need.

1 2 3 4<section itemscope itemtype="http://schema.org/Person"> ... </section>

Once the scope and type of the item have been determined, properties may then be set. These properties are identified by different elements which include the itemprop attribute. The value of this attribute determines what property is being referenced, and the content within the element itself most commonly determines the value of the property.

1 2 3 4<section itemscope itemtype="http://schema.org/Person"> <h2 itemprop="name">Shay Howe</h2> </section>

Some elements, however, do not get their itemprop value from the content within the element. Instead, their value is determined from the value of another attribute on the element. The table below outlines these one-off elements and what attribute is used for their property value.

Element Value
<meta> content attribute
<audio>, <embed>, <iframe>, <img>, <source>, <video> src attribute
<a>, <area>, <link> href attribute
<object> data attribute
<time> datetime attribute

Person Microdata

When referring to a person the person microdata library should be used. Below is an example of what a person microdata item might look like. Please notice, the person item type is used, as is the postal address item type within it. Also, please notice the different item properties and their corresponding values.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Shay Howe Shay Howe

Designer and Front-end Developer
600 W. Chicago Ave. Chicago, IL 60654

Person Microdata Demo

Please keep in mind, this code is for an individual person. Should you wish to refer to an organization, a more specific organization microdata library should be followed.

Event Microdata

The event microdata is very similar to that of the person microdata, however it uses the event microdata library instead. Common property similarities between the two can be identified, as can some of the nested item types.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16

175 N. State St.

Chicago, IL 60601

Event Microdata Demo

Microdata provides a lot of ways to further extend the content of a page. We have only touched the surface here. Further information on microdata may be found at Dive Into HTML5 Microdata and WHATWG Microdata.

WAI-ARIA

WAI-ARIA, also know as Web Accessibility Initiative — Accessible Rich Internet Applications, is a specification that helps make web pages and applications more accessible to those with disabilities. Specifically, WAI-ARIA helps define roles (for what blocks of content do), states (for how blocks of content are configured), and additional properties to support assistive technologies.

Roles

Setting WAI-ARIA roles is accomplished using the role attribute. These roles then specify what certain elements and blocks of content do on a page.

1 2<header role="banner">...</header>

WAI-ARIA roles break down into four different categories, including abstract, widget, document structure, and landmark roles. For this lesson we will focus primarily on the document structure and landmark roles. Document structure roles define the organizational structure of content on a page, while landmark roles define the regions of a page. Specific role values for each of these categories are broken out below.

Document Structure Roles

  • article
  • columnheader
  • definition
  • directory
  • document
  • group
  • heading
  • img
  • list
  • listitem
  • math
  • note
  • presentation
  • region
  • row
  • rowheader
  • separator
  • toolbar

Landmark Roles

  • application
  • banner
  • complementary
  • contentinfo
  • form
  • main
  • navigation
  • search

HTML5 introduced a handful of new structural elements which commonly match up against the document structure and landmark roles. Exactly how these roles match up against specific elements may be seen below. Please notice, the header and footer elements do not have an implied role, and the acceptable roles for these elements may only be used once per page. That said, if you have multiple header and footer elements on a page the banner and contentinfo roles should be applied on the elements directly tied to the document from a top level perspective, not elements nested within other regions of the document structure.

Element Implied Role Acceptable Roles
article article application, article, document, or main
aside complementary complementary, note, or search
footer contentinfo (Only once per page)
header banner (Only once per page)
nav navigation navigation
section region alert, alertdialog, application, contentinfo, dialog, document, log, main, marquee, region, search, or status

Combining the elements with their matched roles in HTML5 would look like the following code snippet.

1 2 3 4 5 6 7 8 9<header role="banner"> <nav role="navigation">...</nav> </header> <article role="article"> <section role="region">...</section> </article> <aside role="complementary">...</aside> <footer role="contentinfo">...</footer>

States & Properties

In combination with WAI-ARIA roles there are also states and properties which help inform assistive technologies how content is configured. Like roles, the states and properties are broken into four categories, including widget attributes, live region attributes, drag-and-drop attributes, and relationship attributes

The widget attributes support widget roles and are specific to the user interface and where users take actions. The live region attributes may be applied to any element and are used to indicate content changes for assistive technologies, on page alerts and notifications for example. Drag-and-drop attributes supply information about drag-and-drop interface elements and provide alternate behaviors to assistive technologies. Lastly, relationship attributes outline the relationship between elements when the document structure cannot be determined.

Scroll to Top