An Introduction to HTML, CSS & JavaScript for anyone & everyone

Forked and updated by Abraham Velazquez ( @lunaroja)
Original content by Lea Verou ( @LeaVerou)

HTML

Structure

“What does it mean?”

.html

CSS

Presentation

“How does it look?”

.css

JavaScript

Behavior

“What does it do?”

.js
Hello <em>world</em>! Open page in new tab
Hello
<a href="http://ft.com/world">​world </a>
Open page in new tab
Attributes allow us to control parameters of each element
  • Even if we don’t add <html>, <head>, and <body> elements, the browser will do it for us.
  • The browser offers us Developer Tools that allow us to peek under the hood and inspect the current state of the page and even modify it.
  • Note that some CSS is applied anyway, from the browser.

Our DOM Tree

  • The browser’s internal model of our HTML is called the DOM Tree
  • It’s a hierarchy of objects of different types, such as:
    • Document : This is the root node, and does not correspond to any HTML element.
    • HTMLElement : Every HTML element, such as html, body, or em is of this type. Usually, they merely inherit from HTMLElement , and are an instance of a more specific type such as HTMLHtmlElement , HTMLBodyElement and so on.
    • Text : Text nodes, such as "Hello ", "world", and "!" in our example. These never contain any other element, they are always leaves.
    • Comment : HTML comments ( <!-- like this -->) are represented by objects of this type.
  • We can interact with, and manipulate the DOM tree via JavaScript!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My first page!</title> </head> <body> Page Content goes here! </body> </html> Open page in new tab

Heading 1

Heading 2

Heading 3

Heading 4

Heading 5
Heading 6

Paragraph

  • 6 levels of headings
  • Do not use just to make text bigger, it breaks navigation for visually impaired users. Use CSS instead, which gives you more control anyway.
  • Use <h1> only once per document

Haystack Group

<a> element specification

  • a elements let you link to other websites or even places in the current page.
  • The href attribute contains the link target, which is an absolute or relative (to the current page) URL
  • The content of the link is the text presented. Sadly there is no shortcut if you want to show the URL itself, you have to duplicate it (or automate this via CSS or JS).
  • To link to a specific place in a page, you need to find an element with an id attribute near that place. Then, you can just add #id to the URL.
  • You can link to specific places in the current page as well, if you just use #yourId as the URL.
  • Item 1
  • Item 2
  1. Item 1
  2. Item 2
First name:
Lea
Last name:
Verou
  • There are three types of lists: unordered lists ( <ul>), ordered lists ( <ol>), and definition lists ( <dl>) for key-value pairs
A kitten, roughly 3 weeks old

  • The <input> element can generate a wide variety of form controls, differentiated by the type attribute. If no type attribute is present, type="text" is assumed.
  • The following only applies to textual inputs ( text, url, email, tel etc):
    • The placeholder attribute shows placeholder text when the field is empty. This is available on <textarea> too.
    • The pattern attribute allows you to restrict input. This does not currently work on <textarea>s, but there are efforts to make it so.
  • In numerical and date inputs ( number, range, date, time etc), the min and max attributes allow you to restrict the range of input.
  • On number and range inputs, you can use the step attribute to control the increment (1 by default).

  • Group radio buttons via the name attribute.
  • Set checked state on checkbox and radio buttons via the checked attribute
  • <label> elements are very useful for all form controls, but especially checkboxes and radios as they increase the target area!
  • Depending on the number of options, different form controls are more appropriate for usability:
    • For < 4 options, prefer radios, as they are the most efficient.
    • Between 5-20 options, <select> menus are ideal
    • For longer than 20 options, search time for <select> menus becomes longer than typing the first few characters. In those cases, use <input> with <datalist for autocomplete)
  • The <button> element creates buttons.
  • These buttons don’t do anything by themselves, but you can make them useful via JavaScript or <form> elements.
  • The action attribute of <form> elements controls which file will receive the submission. By default it's the current file.
  • What’s submitted? Only elements that are enabled and have a name attribute.

HTML

h1 { color: white; background: black; }
  • The selector tells the browser which elements the rule is about, in this case h1 headings.
  • Declarations are property-value pairs. Each declaration controls a certain stylistic aspect.
  • Declarations are separated by semicolons. The last semicolon is optional (but recommended).
  • Here we can see two CSS properties: color which sets the text color, and background which sets the background.

			<!DOCTYPE html>
			<html>
			<head>
				<link rel="stylesheet" href="style.css">
				<style>
					h1 {
						color: white;
						background: black;
					}
				</style>
			</head>
			<body>
				<h1>Title</h1>
			</body>
			</html>
		

3 ways to apply CSS to your page:

  • Via an external file and the link element. This is the recommended way.
  • By writing CSS in the style element
  • For one-off cases, by using the style attribute
  • Both link and style elements are only supposed to go in the head.

Simple Selectors

Most Common selectors element { } .class { } #id { }
  • The universal selector, type selector, class selector, id selector, attribute selectors, pseudo-classes are called simple selectors
  • Concatenating simple selectors intersects them (i.e. it is equivalent to an AND operation). The result is called a Compound Selector E.g. a.docs:hover matches an <a> element with the class docs that is currently being hovered.

			<!DOCTYPE html>
			<html>
			<head>
				<link rel="stylesheet" href="style.css">
				<style>
					.headline {
						color: white;
						background: black;
					}
				</style>
			</head>
			<body>
				<h1 class="headline">Title</h1>
			</body>
			</html>
		

3 ways to apply CSS to your page:

  • Via an external file and the link element. This is the recommended way.
  • By writing CSS in the style element
  • For one-off cases, by using the style attribute
  • Both link and style elements are only supposed to go in the head.

My first CSS code

One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into a horrible vermin.

He lay on his armour-like back, and if he lifted his head a little he could see his brown belly, slightly domed and divided by arches into stiff sections.

The bedding was hardly able to cover it and seemed ready to slide off any moment.

His many legs, pitifully thin compared with the size of the rest of him, waved about helplessly as he looked. "What's happened to me? " he thought. It wasn't a dream.

  • Here we can see our first few CSS properties:
    • font-family: Sets the font, in order of preference. Because on the Web you don’t exactly know which fonts the user has installed, you provide a list of fonts with a generic fallback at the end.
    • color: Sets the text color (which is also the default color for several other effects, such as borders and shadows)
    • hyphens: Enables hyphenation
    • text-decoration: Sets or (in this case) cancels text underline/overline.
  • We can also modify CSS via the Styles tab in the Elements panel of the dev tools. This also shows us what CSS applies each time.
  • This little piggy went to market
  • This little piggy stayed home
  • This little piggy had roast beef
  • This little piggy had none
  • And this little piggy cried wee wee wee all the way home
  • Some properties are inherited by default, and some are not.
  • Use the value inherit to inherit from a non-inherited property and the value initial to reset an inherited property.
  • Inherited declarations always have lower priority than those targeting the element directly.
  • RGB is modeled after 8 bit subpixel voltage, not human usability. It's very hard to adjust a color.
  • Hex colors are the least intuitive format: It’s RGB that is additionally hex-encoded! Mainly useful for copying from a color picker.
  • Named colors are readable, but few, irregularly distributed and often internally inconsistent (e.g. darkgray is lighter than gray!)
  • HSL is probably the most human-friendly out of the currently supported formats, but has its issues too (e.g. hsl(60, 100%, 50%) and hsl(240, 100%, 50%) have the same HSL lightness, but are they equally light?)
  • rgba() and hsla() accept a 4th parameter for alpha (i.e. transparency.)
  • Resources:
  • The background-image property sets the background to the specified image(s).
  • You can link to images via the url function, or generate them via the several gradient functions:
    • linear-gradient
    • repeating-linear-gradient
    • radial-gradient
    • repeating-radial-gradient
    Gradients can be very powerful, as illustrated by this gallery.
  • There is a bunch more background-related properties to control aspects of the background:
    • background-color
    • background-repeat
    • background-size
    • background-position
    • background-clip
    • background-origin
    • background-attachment
  • You can also use the background property to specify all these at once. Because background is a property that is defined in terms of other sub-properties, we say it’s a shorthand (and its properties are longhands).
  • Caveat: Every time you use a shorthand, you’re setting all its longhands, whether you specified values for them or not!
  • Both background and all its longhands (except background-color) accept multiple comma-separated values. This is very useful for creating "layers" of backgrounds.
Bacon ipsum dolor amet alcatra meatball burgdoggen, venison ham hock turkey shoulder pancetta swine brisket jowl.
The Box Model
  • padding controls the spacing from the element’s content to its edge. margin specifies the spacing from the element’s edge to the elements around it. border allows you to specify a visible border. It’s placed outside the padding.
  • Padding & border widths are added to width and height, not subtracted from it.
  • You can change that with box-sizing: border-box
  • You can use the browser developer tools to inspect the box model, via the "Computed" tab in the Elements panel.
  • There are more units besides px that you can use anywhere a length is required!. Some useful units are:
    • % refers to a different thing depending on the property. Look it up on a case-by-case basis!
    • em is relative the current font size
    • rem is relative to the current font size of the html element
    • ch represents the width of the "0" glyph in the current font. This is useful in monospaced fonts where every character has the same width.
    • vw is a percentage of the viewport width ( 100vw = viewport width)
    • vh is a percentage of the viewport height ( 100vh = viewport height)
  • Font-relative units are useful in making components that scale by changing one property (the font-size).
  • Viewport-relative units are useful in making layouts that scale nicely with the viewport size.
  • Use calc() to perform calculations between different units.
💩
  • Animations are more complex than transitions but give us more control.
  • We define animations with the @keyframes rule.
  • We apply animations to elements with the animation property.
  • The animation property is actually a shorthand for:
    • animation-name: Which animation to run?
    • animation-duration: How long should each iteration last?
    • animation-delay: Any delay before it starts?
    • animation-iteration-count: How many times should it play? (number or infinite)
    • animation-timing-function: How should it progress over time?
    • animation-direction: Should any iterations be reversed?
    • animation-fill-mode: How should it behave before and after it’s applied?
    • animation-play-state: Should it be paused?
  • At a minimum, a name and duration is needed for an animation to play.
  • All animation properties accept comma-separated lists of parameters, to apply multiple animations on the same element.
  • We can monitor the progress of CSS animations via the animationstart, animationiteration, and animationend events.
  • display: flex enables Flexbox layout on an element. This element becomes the Flex Container and its children are called Flex Items.
  • flex: N defines the proportion that a flex item spreads over.
  • flex-direction: column on the flex container makes the items flow from top to bottom
  • align-items and justify-content on the flex container specify alignment in each direction. Which direction depends on the value of flex-direction
  • CSS

    JavaScript
    (Open your consoles!)

    • The Console tab allows us to experiment with JavaScript.
    • $0 always refers to the currently selected element. $1 to the previously selected element, $2 to the one before it and so on.
    • element.textContent gives us the content of an element as text. Try changing it!
    • Other useful properties you could play with:
      • parentNode
      • childNodes
      • children
      • previousSibling
      • nodeType
    
    				<!DOCTYPE html>
    				<html>
    				<head>
    					<script src="code.js"></script>
    				</head>
    				<body>
    					<script>
    						console.log("hi");
    					</script>
    				</body>
    				</html>
    			

    2 ways to run JS in your page:

    • Via an external file and the script element. This is the recommended way.
    • By writing JS inside the script element
    • script elements can go anywhere in your HTML, they are not restricted to the head.
    • You can define variables with let.
    • You can output content to the console with console.log() . This is very useful for debugging.
    • Open the console and click run to see the result.
    • Arrays are defined with brackets ( [])
    • Functions are defined in many ways. We have already seen function(){ /* code */ }. The shortest is the notation shown here ( arrow functions ).
    • The map() method of arrays allows you to transform them into something else.
    • Activity: Go to mit.edu again, and create an array with the textual content of all headings.
    • Object literals are defined via braces ( {}). They are similar to dictionaries or maps in other languages.
    • There are also constructors, just like other OOP languages. In fact, object literals are implicitly calling new Object() and the brackets notation for arrays is implicitly calling new Array().
    • Property names can have any character. Property names that only consist of letters, numbers, $, _ don’t need quotes.
    • Property names can be added or deleted at any point.
    • Take note of the two different notations to refer to property values. The brackets notation can be used for computed properties too!
    • Object literals are defined via braces ( {}). They are similar to dictionaries or maps in other languages.
    • There are also constructors, just like other OOP languages. In fact, object literals are implicitly calling new Object() and the brackets notation for arrays is implicitly calling new Array().
    • Property names can have any character. Property names that only consist of letters, numbers, $, _ don’t need quotes.
    • Property names can be added or deleted at any point.
    • Take note of the two different notations to refer to property values. The brackets notation can be used for computed properties too!
    • In JavaScript everything is an object, even functions!
    • Functions in JS are just objects of type Function that can also be called (via parentheses).
    • Important to distinguish reference to a function (no parentheses) from calling a function (with parentheses).
    • You can assign functions to variables.

    JavaScript