HTML/CSS Reference for DMET 155/355

Posted on:  


![Directory](https://image-control-storage.s3.amazonaws.com/2023/03/13091607/file_structure-1-1024x456.jpg)
[Basic Directory Structure for a Static Site](#html-tag)

<html>
<body>
    This is my first web page
</body>
</html>

The first line on the top, ``, is a document type declaration that lets the browser know which flavor of HTML you’re using (HTML5, in this case).

<html> the opening tag kicks things off and tells the browser that everything between that and the </html> closing tag is an HTML document. The stuff between <body> and </body> The document’s main conten twill appear in the browser window.

HTML Tag: html

A web page’s root element. The big daddy. The ancestor of all elements. The element that wraps its arms around all other elements.


<html lang="en">
    <head>
        <title>The Title of the Page</title>
    </head>
    <body>
        <!-- content -->
    </body>
</html>

Elements

Tags tend not to do much more than mark the beginning and end of an element. Elements are the bits that makeup web pages. You would say, for example, that everything that is in between (and includes) the <body> and </body> tags is the body element. As another example, “<title>” And “</title>” are tags, “<title>Rumple Stiltskin</title>” is a title element.

Attributes

Tags can also have attributes, which are extra bits of information. Attributes appear inside the opening tag and their values sit inside quotation marks. They look something like <tag attribute="value">Margarine</tag>. We will come across tags with attributes later.

Once again, quotation marks aren’t always essential but it is a good-practice convention HTML Dog uses for consistency and clarity. We suggest you do the same.

Elements

Tags tend not to do much more than mark the beginning and end of an element. Elements are the bits that make up web pages. You would say, for example, that everything that is in between (and includes) the <body> and </body> tags is the body element. As another example, whereas “<title>” and “</title>” are tags, “<title>Rumple Stiltskin</title>” is a title element.

<title>” and “</title>” are tags, “<title>This is the title of the page</title>” is a title element.

HTML Tag: head

Where metadata — information about the document — is placed. It should be the first element inside an html element.

A title element is required within the head element. meta, style, base, link, and script can also be used.

head is required and it should be used just once. It should start immediately after the opening html tag and end directly before the opening body tag.


<html lang="en">
    <head>
        <title>This is the title of the page</title>
        <link href="style.css" rel="stylesheet">
    </head>
    <body>
        <!-- content -->
    </body>
</html>

Page Titles

All HTML pages should have a page title.

To add a title to your page, change your code so that it looks like this:

We have added two new elements here, that start with the head tag and the title tag (and see how both of these close).

The head element (that which starts with the <head> opening tag and ends with the </head> closing tag) appears before the body element (starting with <body> and ending with </body>) and contains information about the page. The information in the head element does not appear in the browser window.


<html>
<head>
    <title>My first web page</title>
</head>
<body>
    This is my first web page
</body>
</html>

HTML Tag: body

The main content area of an HTML document.

You must use this element and it should be used just once. It should start immediately after the closing head tag and end directly before the closing html tag.


<html lang="en">
    <head>
        <title>Content</title>
    </head>
    <body>
        <!-- Content -->
    </body>
</html>

Paragraphs

Now that you have the basic structure of an HTML document, you can explore content a bit.

Go back to your text editor and add another line to your page:


<html>
<head>
    <title>My first web page</title>
</head>
<body>
    This is my first web page
</body>
</html>

Look at the document in your browser.

You might have expected your document to appear as you typed it, on two lines, but instead you should see something like this:

<strong>This is my first web page How exciting.</strong>

This is because web browsers don’t usually notice what line your code is on. It also doesn’t take any notice of spaces (you would get the same result if you typed “This is my first web page”.

If you want text to appear on different lines or, rather, if you intend there to be two distinct blocks of text (because, remember, HTML is about meaning, not presentation), you need to state that explicitly.

Change your two lines of content so that they look like this:

<p>This is my first web page</p>
<p>How exciting</p>

The p tag is used for paragraphs.

Look at the results of this. The two lines will now appear on two lines because the browser recognizes them as separate paragraphs.

Think of the HTML content as a book – with paragraphs where appropriate.


## **Assignment**
- 1. Create an HTML page using the above code. Remember to use all the examples in this exercise. - html - head - title - body - h1 - p - h2 - ul - ol - li - a - strong

Emphasis

You can emphasize text in a paragraph using em (emphasis) and strong (strong importance).

<p>That <em>is</em> interesting.</p>

Line breaks

The line-break tag can also be used to separate lines like this:


This is my first web page<strong><br></strong>
How exciting

There’s no content involved in breaking lines so there is no closing tag.

It could be tempting to over-use line breaks and br shouldn’t be used if two blocks of text are intended to be separate from one another (because if that’s what you want to do you probably want the p tag).

Lists

There are three types of list; unordered lists, ordered lists and definition lists.

Unordered lists and ordered lists work the same way, except that the former is used for non-sequential lists with list items usually preceded by bullets and the latter is for sequential lists, which are normally represented by incremental numbers.

The <strong>ul</strong> tag is used to define unordered lists and the <strong>o</strong>l tag is used to define ordered lists. Inside the lists, the <strong>li</strong> tag is used to define each list item.



<html>

<head>
    <title>My first web page</title>
</head>

<body>
    <h1>My first web page</h1>

    <h2>What this is</h2>
    <p>A simple page put together using HTML</p>

    <h2>Why this is</h2>
    <ul>
        <li>To learn HTML</li>
        <li>Apple</li>
        <li>This is an example of a sentence in a list</li>
    </ul>

</body>

</html>

If you look at this in your browser, you will see a bulleted list. Change the <strong>ul</strong> tags to ol and you will see that the list will become numbered.

Lists can also be included in lists to form a structured hierarchy of items.

Replace the above list code with the following:

<ul>
    <li>To learn HTML</li>
    <li>
        To show off
        <ol>
            <li>To my boss</li>
            <li>To my friends</li>
            <li>To my cat</li>
            <li>Hello to all my friends</li>
        </ol>
    </li>
    <li>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium.</li>
</ul>

A list within a list. And you could put another list within that. And another within that. And so on and so forth.

Links

So far you’ve been making a stand-alone web page, which is all very well and nice, but what makes the Internet so special is that it all links together.

The “H” and “T” in “HTML” stand for “hypertext”, which means a system of linked text.

An anchor tag (a) is used to define a link, but you must also add something to the anchor tag — the link’s destination.

Add this to your document:



<html>

<head>
    <title>My first web page</title>
</head>

<body>

    <h1>My first web page</h1>

    <h2>What this is</h2>
    <p>A simple page put together using HTML</p>

    <h2>Why this is</h2>
    <p>To learn HTML</p>

    <h2>ESU's Homepage</h2>
    <p><a href="http://www.esu.edu">ESU</a></p>

</body>

</html>

The destination of the link is defined in the href attribute of the tag. The link can be absolute, such as “https://www.ndangelo.com”, or it can be relative to the current page.

So if, for example, you had another file called “flyingmoss.html” in the same directory then the line of code would be <a href="flyingmoss.html">The miracle of moss in flight</a> or something like this.

A link does not have to link to another HTML file, it can link to any file anywhere on the web.

Images

The web is not just about text, it is a multi-media extravaganza and the most common form of sparkle is the image.

The <strong>img</strong> tag is used to put an image in an HTML document and it looks like this:

<img src="test-image.gif" width="120" height="90" alt="Test">

The src attribute tells the browser where to find the image. Like the a tag, this can be absolute, as the above example demonstrates, but is usually relative. For example, if you create your own image and save it as “alien.jpg” in a directory called “images” then the code would be <img src="images/alien.jpg"...

The width and height attributes are necessary because if they are excluded, the browser will tend to calculate the size as the image loads, instead of when the page loads, which means that the layout of the document may jump around while the page is loading.

The alt attribute is the alternative description. This is an accessibility consideration, providing meaningful information for users who cannot see the image (if they are visually impaired).

Putting It All Together

The following code incorporates all of the methods that have been explained in the previous pages:

Assignment

Please remember the text below: Create your own HTML page using the code provided. Ensure that the content on the page is original. Use your own images, text, and layout. Make sure to incorporate all the tags in the example. We will include a new link on your index page that will lead to this new page.



<html>

<head>

    <title>My first web page</title>

    <!-- This is a comment, by the way -->

</head>

<body>

<h1>My first web page</h1>

<h2>What this is</h2>
<p>A simple page put together using HTML. <em>I said a simple page put together using HTML.</em> A simple page put together using HTML. A simple page put together using HTML. A simple page put together using HTML. A simple page put together using HTML. A simple page put together using HTML. A simple page put together using HTML. A simple page put together using HTML.</p>

<h2>Why this is</h2>
<ul>
    <li>To learn HTML</li>
    <li>
        To illustrate
        <ol>
            <li>To my boss</li>
            <li>To my friends</li>
            <li>To my cat</li>
            <li>I'm not sure what</li>
        </ol>
    </li>
    <li>Some interesting content</li>
</ul>

<h2>Where to find the tutorial</h2>
<p><a href="http://www.esu.edu"><img src="test-image.gif" width="120" height="90" alt="ESU"></a></p>


<h3>Some random form</h3>
<p><strong>Note:</strong> It looks the part, but won't function.</p>


</body>

</html>

Span and Div

HTML is all about applying meaning to content. Whereas most HTML tags apply meaning (<strong>p</strong> makes a paragraph, <strong>h1</strong> makes a heading etc.), the span and div tags apply no meaning at all. They are used extensively in conjunction with CSS.

They are used to group together a chunk of HTML and hook some information onto that chunk, most commonly with the attributes class and id to associate the element with a class or id CSS selector.

The difference between <strong>span</strong> and <strong>div</strong> is that a <strong>span</strong> element is in-line and usually used for small snippets of HTML inside a line (such as inside a paragraph), whereas a <strong>div</strong> (division) element is block-line (which is equivalent to having a line-break before and after it) and used to group larger snippets of code.


<div id="scissors">
    <p>This is <span class="paper">crazy</span></p>
</div>

<strong>div</strong>, and especially <strong>span</strong>, shouldn’t be used that often. Whenever there is a sensible alternative that should be used instead. For example, if you want to emphasize the word “crazy” and the class “paper” is adding italics for visual emphasis, then, for richer, more meaningful content, the code might look like this:


<div id="scissors">
    <p>This is <strong><em class="paper"></strong>crazy<strong></em></strong></p>
</div>

While they are not replacements for the div tag, HTML 5 introduces several tags used for grouping blocks of code together and adding meaning at the same time. Such as article, header, footer.

CSS Cheat Sheet

![CSS Cheat Sheet](https://image-control-storage.s3.amazonaws.com/2023/08/06104531/css_cheat_2-1-1024x728.png)


<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Index Page</title>

<style type="text/css">

	@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,400;0,500;0,600;1,400&display=swap');
	
	.wrapper {
		font-family: 'Montserrat', sans-serif;
		width: 400px;
		height: 800px;
		border: solid 2px red;
		margin: auto;
		text-align: center;
	}

	ul, li {

	text-align: center;
	list-style-type: none;
	padding-right: 20px;

	}



</style>

</head>
<body>

	<div class="wrapper">
		
<h1>Intro to Web Assignments</h1>

<br><br><br><br>

<ul>

<li><a href="content.html" target="_blank">Content</a></li>
<li><a href="start.html" target="_blank">start</a></li>


</ul>

<img src="images/nd_logo_blog-2.png">
	</div>

</body>
</html>

See the Pen Layouts and the Box Model by Christina Truong (@christinatruong) on CodePen.

The following is some code I created on codepen.io. It includes div nesting, which we covered in class. The “pen” also has advanced CSS to make each div stand out.

From: https://www.htmldog.com/

See the Pen albers by Nicholas D’Angelo (@ndangelo) on CodePen.

Text: Abbreviations, Quotations, and Code

The basics of defining text using paragraphs (as well as emphasis and line breaks) and headings was covered in the HTML Beginner Tutorial. And for the same reason we use p and h1, h2, etc, there are a number of other tags we should also use to specifically represent other text-types, such as abbreviations, quotations, and computer code.

Abbreviations

abbr is used to markup an abbreviation, a shortened form of a word or phrase.

The expanded phrase that the abbreviation represents can be defined in the value of the title attribute. This is optional but recommended.


<p>This web site is about <strong><abbr title="HyperText Markup Language">HTML</abbr></strong> and <strong><abbr title="Cascading Style Sheets">CSS</abbr></strong>.</p>

Quotations

<strong>blockquote</strong> and q are used for quotations. <strong>blockquote</strong> is generally used for standalone often multi-line quotations whereas <strong>q</strong> is used for shorter, in-line quotations.

If the source of the quotation can be found on the Web, the cite attribute can be used to point to its origin.


<p>So I asked Bob about quotations on the Web and he said <strong><q></strong>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium<strong></q></strong>. It said:</p>

<strong><blockquote cite="https://</strong>ndangelo.com<strong>"></strong>
    <p>blockquote and q are used for quotations. blockquote is generally used for standalone often multi-line quotations whereas q is used for shorter, in-line quotations.</p>
<strong></blockquote></strong>

Blockquotes work very nicely with the HTML5 elements <strong>figure</strong> and <strong>figcaption</strong>, enabling a nice, semantic way to group a quotation with a citation:


<figure>
    <blockquote>[Big old quotation about evolution]</blockquote>
    <figcaption>Charles Darwin</figcaption>
</figure>

Citations

To make things nice and confusing, as well as a <strong>cite</strong> attribute, there is also a <strong>cite</strong> tag. This can be used to define the title of a work, such as a book.


<p>According to <strong><cite>My tax bill</cite></strong>, Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium</q>.</p>

Code

<strong>code</strong> is used to represent any form of computer code. Further, <strong>var</strong> can be used for variables (which could be a variable in anything, not just in code – it could be a variable in an equation, for example), <strong>samp</strong> for sample output, and <strong>kbd</strong> (keyboard) for user input.


<p>If you add the line <strong><var>provide</var> = true;</strong> to the <strong>planet</strong> subroutine and then type <strong><kbd>Help</kbd></strong> into the console, Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium <strong><samp>Help!</samp></strong> error sit voluptatem.</p>

Preformatted text

<strong>pre</strong> is preformatted text and is unusual in HTML tags in that it takes notice of every character in it, including the white space (whereas other elements will ignore a consecutive space or a line-break, for example). It is most commonly used for blocks of code, where spacing, such as indentations, can be relevant.


<strong></strong>
&lt;div id="intro"&gt;
    &lt;h1&gt;Some heading&lt;/h1&gt;
    &lt;p&gt;Some paragraph paragraph thing thing thingy.&lt;/p&gt;
&lt;/div&gt;
<strong></strong>

As an example, <strong>pre</strong> and <strong>code</strong> are used extensively throughout this site. The code blocks, such as the one above, are <strong>code</strong> elements inside <strong>pre</strong> elements. In-line references to tags and properties are simply <strong>code</strong> elements, often inside <strong>a</strong> elements to link to the reference section.

Meta Tags

Meta tags don’t do anything to the content presented in the browser window, but search engines use them to catalog information about the web page.

There is one <strong>meta</strong> tag which can be used as many times as you desire inside a <strong>head</strong> element and they can contain the attributes charset, name, http-equiv, and content.

When the name or <strong>http-equiv</strong> attribute is used, which is then used in conjunction with them to apply meta data.

Names

The name attribute can be anything you like. The most commonly used names are author, description, and keywords. <strong>author</strong> is used to explicitly state one of the HTML page’s authors and <strong>description</strong> is often used by search engines (such as Google) to display a web page description in its search results.

The reason why <strong>meta</strong> tags used to be so important was because they were relied on by search engines to build a profile of a web page. The <strong>keywords</strong> meta data was used extensively, for example. Nowadays, however, most search engines use the actual content of the page itself.

HTTP Equivalents

The <strong>http-equiv</strong> attribute can be used instead of the name attribute and will make an HTTP header, which is information sent to the server where the web page is held. The attribute should rarely be used (although see charset note, below) but the value can be:

The charset attribute can be used as a shorthand method to define an HTML document’s character set, which is always a good thing to do. <strong><meta charset="utf-8"></strong> is the same as <meta http-equiv="content-type" content="text/html; charset=utf-8">.


<head>
    <title>Air conditioners? YEAH conditioners!</title>
<strong>    <meta charset="utf-8"></strong>
<strong>    <meta http-equiv="refresh" content="3"></strong><!--not recommended for sane people-->
<strong>    <meta name="description" content="This is my really, really, REALLY exciting web page about air conditioners"></strong>
    ...

Tables: rowspan and colspan

Tables may have seemed complicated. Visualizing a two-dimensional grid from one-dimensional lines of code can be quite difficult.

Well, it gets trickier. All thanks to the rowspan and colspan attributes.


<table>
    <tr>
        <strong><th></strong>Column 1 heading<strong></th></strong>
        <strong><th></strong>Column 2 heading<strong></th></strong>
        <strong><th></strong>Column 3 heading<strong></th></strong>
    </tr>
    <tr>
        <td>Row 2, cell 1</td>
        <td <strong>colspan="2"</strong>>Row 2, cell 2, also spanning Row 2, cell 3</td>
    </tr>
    <tr>
        <td <strong>rowspan="2"</strong>>Row 3, cell 1, also spanning Row 4, cell 1</td>
        <td>Row 3, cell 2</td>
        <td>Row 3, cell 3</td>
    </tr>
    <tr>
        <td>Row 4, cell 2</td>
        <td>Row 4, cell 3</td>
    </tr>
</table>

The first difference is that the td tags of the first row have been replaced with th tags. Whereas a td is a standard data cell, th is a header cell. As with td elements, these must be enclosed inside tr elements.

See the Pen Table Example 1 by Nicholas D’Angelo (@ndangelo) on CodePen.

## **Assignment**
  1. Create a table with six rows.
  2. Vary the width of the table data for each row (use rowspan, and refer to the embedded codepen example.
  3. Create three table headers (the example uses three.)
  4. Use column span to create table data cells.
  5. Note: rowspan is the height of the column. Column span is the width of the cells.
  6. Fill the cells with at least three images. The rest can be filled with text.
  7. Use CSS to style the table for easy viewing.
  8. This can be challenging, take your time.

Spanning columns and rows

colspan and rowspan attributes have also been used in some of the td tags. If you look at this code in a browser, you will see that on the second row there are now two cells instead of three, the second cell spanning the second and third column. The colspan attribute, which means “column span” will span the cell over the number of cells that is specified. This means, in this example, that there is no need for a third td element — two cells are merged into one.

The rowspan attribute is similar to colspan, except, obviously, it will span across rows rather than columns. Again, the cells that it spans should be removed. In this example, because it spans over the fourth row, there are only two cells in that row.

As with the simpler 3×4, 12-cell table, the numbers on these tables with merged cells should also add up. Although there are only 10 cells in this example, there are 2 spans.

Description Lists

Description lists are quite often forgotten. This is maybe because they are much more specific than ordered and unordered lists and therefore less useful, generally, but where there is a list of terms and descriptions (such as a glossary), a description list is your go-to-element.

dl gets the ball rolling, similar to the ul and ol elements, establishing the list. Rather than containing li elements, though, description lists have dt elements, which are the terms, followed by dd elements, which are the descriptions associated to the dt elements.

There doesn’t have to be one dt followed by one dd, there can be any number of either. For example, if there are a number of words that have the same meaning, there might be a number of dt’s followed by one dd. If you have one word that means various different things, there might be one dt followed by several dd’s.

See the Pen Glossary by Nicholas D’Angelo (@ndangelo) on CodePen.


<h1>Some random glossary thing</h1>
<dl>
    <dt>HTML</dt>
    <dd>Abbreviation for HyperText Markup Language - a language used to make web pages.</dd>

    <dt>Dog</dt>
    <dd>Any carnivorous animal belonging to the family Canidae.</dd>
    <dd>The domesticated sub-species of the family Canidae, Canis lupus familiaris.</dd>

    <dt>juice</dt>
    <dt>beer</dt>
    <dt>Milk</dt>
    <dd>A white liquid produced by cows and used for human consumption.</dd>
</dl>

Note that the <strong>img</strong> element doesn’t need an alt attribute IF the <strong>figcaption</strong> (that’s “figure caption”, in case you need it spelling out) does that job.

## **Assignment** (Intro & Advanced)
  1. Add Images to each definition. Take a look at the “figure” tag example.
  2. Included the following in a wrapper.
  3. Use a unique style in CSS. The codepen example is simple CSS. Have fun with this! add rounded corners, drop shadows etc…
  4. Include 10 terms and definitions.

<strong><figure></strong>
    <img src="obelisk.jpg">
    <strong><figcaption></strong>Tixall Obelisk<strong></figcaption></strong>
<strong></figure></strong>

See the Pen figure and caption by Nicholas D’Angelo (@ndangelo) on CodePen.

Text: Addresses, Definitions, Bi-directional, and Editorial

OK, so we should all be know by now that there are lots of tags for text. We’ve done paragraphs, we’ve done headings, we’ve even done abbreviations, quotations, and code. And there are several other, more obscure tags that can be used. Obscure because you won’t find them plastered around the Web, not because they are unhelpful. If you find you have text that fits these elements’ descriptions, you will have a nicer, richer, more meaningful HTML page if you use them.

Addresses

address should be used specifically for the contact details relating either to the entire web page (and so only used once) or to an article element (see Sectioning). It’s isn’t, as it might at first appear, for marking up any old address willy-nilly.

<h3>Author contact details</h3>
<strong><address></strong>
<ul>
    <li>0123-456-7890</li>
    <li>[email protected]</li>
    <li>http://www.noplaceinteresting.com/contactme/</li>
</ul>
<strong></address></strong>

Definition terms

<strong>dfn</strong> is a definition term and is used to highlight the first use of a term. Like <strong>abbr</strong>, the <strong>title</strong> attribute can be used to describe the term.


<p>Bob's <strong><dfn title="Dog">canine</dfn></strong> mother and <strong><dfn title="Horse">equine</dfn></strong> father sat him down and carefully explained that he was an <strong><dfn title="A mutation that combines two or more sets of chromosomes from different species">allopolyploid</dfn></strong> organism.</p>

Bi-directional text

bdo can be used to reverse the direction of the text, and can be used to display languages that read right to left. The value of the required attribute dir can be ltr (left to right) or rtl (right to left).


<bdo dir="rtl">god lmth</bdo>

Editorial

ins and del are used to display editorial insertions and deletions respectively. Strictly speaking, they aren’t limited to text and can be used over whole swathes of content but, typically, they are used in moderation just like “Track Changes” feature in word processors tend to be.

They can have the attributes datetime to indicate when the edit was made and cite, to point to a description as to why the edit has been made.


<p>I have decided to <strong><del datetime="2013-01-26">decrease</del></strong> <strong><ins cite="http://www.icecreamforall.com/changeofpolicy/">increase</ins></strong> the amount of free ice cream that the State will provide for its citizens.</p>

As with traditional word processor-based editing, the ins element is typically shown underlined and the del element is usually displayed with a strikethrough.

Sectioning

While headings do a grand, perfectly valid, job in defining the start of a new section or sub-section in a document, there are a number of elements that can be exploited to establish a cleaner, clearer semantic structure.

Whereas div elements can be used to contain sections, used primarily as scaffolding on which to hang CSS, they don’t hold a great deal of meaning. Sectioning involves a handful of tags that can be used to define specific parts of a page, such as articles, headers, footers, and navigation.

Articles and Sections

An <strong>article</strong> element can be used to mark up a standalone section of content. This could be used just once, if you think of a blog post as an article, for example, or a number of times, if you imagine replicating a traditional newspaper page with numerous articles.

A <strong>section</strong> element represents a more general section and could be used to split up an article, or to represent chapters, for example.


<strong><article></strong>
    <strong><section id="intro"></strong>
        <p>[An introduction]</p>
    <strong></section></strong>
    <strong><section id="main_content"></strong>
        <p>[Content]</p>
    <strong></section></strong>
    <strong><section id="related"></strong>
        <ul>
            <li><a href="that.html">That related article</a></li>
            <li><a href="this.html">This related article</a></li>
        </ul>
    <strong></section></strong>
<strong></article></strong>

See the Pen Sectioning Main by Nicholas D’Angelo (@ndangelo) on CodePen.

## **Assignment**
  1. Create a layout similar to the example above. The <article> tag maybe use as a wrapper however I would use a separate .wrapper style.
  2. Add a new tag called an <aside>. This tag us use to create areas on the left and right of sections. The float: left; or right in CSS will be criticle here.
  3. You will have to experiment with the width and height of sections in order to complete the layout. Remember you are trying to make “boxes and rectangles” to contain content. Use CSS to add a background-color to each section.
  4. Use a new tag <nav>. You may wish to add this above the header or you may wish to include it within it. Add a horizontle nav (Hint: list-stye-type). Use “#” instead of a URL.
  5. Add a google font, and a rollover state to the nav items.

Assignment Create a layout using the above template.

While divs could be used to make these separations (or even if you didn’t need these separations for styling), this provides a much richer, more meaningful document.

The HTML5 specifications suggest that you can use h1 elements at the start of each section, which would become a sub-heading of anything preceding that section (so, in the example above, if you had an h1 immediately following the opening article tag, an h1 immediately after an opening section tag would be a sub-heading of that initial h1). This screws backwards compatibility, however, and any user agents (including screen readers) that don’t understand this won’t apply properly structured heading levels. We suggest sticking to the headings levels you would use if you didn’t use sections (so h1, followed by h2, etc, regardless of the sectioning). This doesn’t break anything or detract from the meaning or semantics.

Headers and Footers

<strong>header</strong> and <strong>footer</strong> provide further specialized, self-descriptive sections:


<body>
<article>
    <strong><header></strong>
        <h1>Alternatively&hellip;</h1>
        <p>[An introduction]</p>
    <strong></header></strong>
    <section id="main_content">
        <p>[Content]</p>
    </section>
    <strong><footer></strong>
        <p>[End notes]</p>
    <strong></footer></strong>
</article>
<strong><footer></strong>
    <p>[Copyright bumf]</p>
<strong></footer></strong>
</body>

The footer is the footer of the section in which it is contained. So, in the above example, the first footer is the footer of the article and the second footer is the footer of the page.

Asides

An aside can be used to represent content that is related to the content surrounding it. Think of pull quotes or snippets of related information in an article:


<section id="main_content">
    <h1>Tixall</h1>
    <p>[All about Tixall]</p>
    <strong><aside></strong>
        <h2>Tixall Obelisk</h2>
        <p>[A short note about Tixall Obelisk]</p>
    <strong></aside></strong>
    <p>[Maybe a bit more about Tixall]</p>
</section>

While we’re at this structure, if you want to include figures, there happens to be two tags for doing just that:


<strong><figure></strong>
    <img src="obelisk.jpg">
    <strong><figcaption></strong>Tixall Obelisk<strong></figcaption></strong>
<strong></figure></strong>

Note that the <strong>img</strong> element doesn’t need an alt attribute IF the <strong>figcaption</strong> (that’s “figure caption”, in case you need it spelled out) does that job.

See the Pen figure and caption by Nicholas D’Angelo (@ndangelo) on CodePen.

Finally, there’s nav, used to mark up a group of navigation links:


<strong><nav id="main_nav"></strong>
    <ul>
        <li><a href="/tutorials/">Tutorials</a></li>
        <li><a href="/techniques/">Techniques</a></li>
        <li><a href="/examples/">Examples</a></li>
        <li><a href="/references/">References</a></li>
    </ul>
<strong></nav></strong>

This could also be used for in-page navigation (<a href="#overthere">... etc.) but it isn’t necessary for every group of links – it is designed for major groupings. A copyright, author, and contact link could sit happily by themselves in a <strong>footer</strong> element, for example.

If you want to style these new HTML 5 elements (and you probably do, right? It’s much nicer than using <div id="content">..., etc) you will experience a problem in older browsers, most notably Internet Explorer versions 8 and earlier, that don’t understand these tags.

From: https://www.htmldog.com/

Box-Sizing and @Media Screen

See the Pen Adaptive Layout Example: Simplified by Nicholas D’Angelo (@ndangelo) on CodePen.

Assignment (We will see how far we get in class)

Take the previous create your own composition using divs, and apply box-sizing and @media_screen. Make sure to include at least six divs that have a background-color. Make sure all divs are nested in a wrapper. The minimum width of your composition should be 400px. The wrapper should expand to contain all your divs. Add at least one image.

Use an external CSS file.

Bonus: use the following CSS to scale your images.

img {
width: 100%;
height: auto;
}


Text: Time, Mark, and “Presentational”

HTML5 adds and amends a handful of tags relating to text. Many of the minor amendments, such as differing attributes in existing tags, have already been covered, but this page looks at two new tags — time and mark — as well as the re-definition of presentational tags.

Time

time is used to make dates and times super-semantically rich.

The text sandwiched in the middle of the opening and closing tag can be any format of date of time – the whole precise lot, or just one part, such as a day. It is made more helpful, however, by the datetime attribute, the value of which should be a machine-readable date and/or time.


<p>Written by Doctor Who on <strong><time datetime="2052-11-21">Thursday 21st November 2052</time></strong>.</p>

Valid datetime values can take the format of a year-month-day date (as above), as a “fuzzy” date, such as “2052-11”, of a time, such as “09:30” (always using a 24-hour clock), or a combination, such as “2052-11-21 09:30”. This can also accommodate time zones and durations.

If the element’s textual content is already machine-readable, you don’t need the datetime attribute, but it is required if it isn’t.

Mark

Text can be highlighted, as if with a marker pen, using <strong>mark</strong>:


<blockquote>
    <p>He wants to play with his <strong><mark>Legos</mark></strong></p>
</blockquote>

<p>The person being quoted is clearly American because, for some odd reason, they pluralise "Lego".</p>

Yes, this is a form of emphasis, literally speaking, but it won’t always be considered emphasis in the original meaning (for example, the person being quoted above isn’t emphasizing “Legos”, the commenter is), hence its inclusion.

Conditional Comments

Conditional comments, which discuss HTML comments that Internet Explorer (up to version 9) interprets differently from other modern browsers, can be formalized as follows:

“The provided comments serve the purpose of selectively delivering specific portions of HTML content exclusively to Internet Explorer versions up to 9. These comments exploit a characteristic of Internet Explorer and are intended to provide a distinct set of instructions to these particular browsers. In contrast, compliant and contemporary web browsers will recognize these comments merely as unobtrusive annotations and proceed without any specific interpretation.”

They have become a commonly used method of latching extra CSS to a document to plaster over holes in these browsers’ display capabilities. So, for example, you might add something like this inside your <strong>head</strong> element:


<link href="everything.css" rel="stylesheet">
<strong><!--[if IE]><link href="stupidie.css" rel="stylesheet"><![endif]--></strong>

Everything between \<!--[if IE]> and <![endif]--> will be picked up by Internet Explorer. So this will bolt on a CSS file as normal, and then, only if the browser is Internet Explorer (in practice, this will be Internet Explorer version 9 and below), it will also apply an extra CSS file patch.

You can also target specific versions of Internet Explorer:

You can also target all versions that are greater or less than a certain number:

There are more options than this which are largely totally unnecessary. Take a look at Microsoft’s own take on it if you feel compelled to find out more.

Conditional comments really are horrible. Necessary, often, at the moment, but horrible. Like all hacks, it is best to avoid them wherever possible. They’re not really there for whacking completely different stylesheets in different browsers, for example. It’s more for small fallbacks so that you can use the scrumptious likes of CSS 3 without compromise. And don’t assume you have to accommodate every stone-age version of IE, either – try and figure out what is sensible for you to support. Are your web site visitors likely to be using IE6? Probably not.

Tables: Columns, Headers, and Footers

So you think you know how to make a table. Sure, you know the table, tr, td and th tags, you’ve even got the rowspan and colspan attributes in your pocket. You can make a really cute little plywood coffee table, but don’t you want to know how to make one of those polished solid wood, glass top dining tables that can take the weight of an oversized elephant?

The Columns Strike Back

Table rows tend to make table columns look rather stupid. They do all the work, as the table is built row by row, leaving the columns feeling quite rejected.

Luckily for those eager columns though, the colgroup and col tags have come to their rescue.

These tags allow you to define the table columns and style them as desired, which is particularly useful if you want certain columns aligned or colored differently, as, without this, you would need to target individual cells.


<table>
    <strong><colgroup></strong>
        <strong><col></strong>
        <strong><col class="alternative"></strong>
        <strong><col></strong>
    <strong></colgroup></strong>
    <tr>
        <td>This</td>
        <td>That</td>
        <td>The other</td>
    </tr>
    <tr>
        <td>Ladybird</td>
        <td>Locust</td>
        <td>Lunch</td>
    </tr>
</table>

In this example, the CSS class “alternative” styles will be applied to the second column, or the second cell in every row.

You can also use the span attribute in a similar way to rowspan and colspan. Using it with the colgroup tag will define the number of rows that the column group will belong to, for example <colgroup span="2"></colgroup> would group the first two columns. Using span in the col tag is usually more useful, and could, for example, be applied to the above example like this:


<table>
    <colgroup>
        <col>
        <col <strong>span="2"</strong> class="alternative">
    </colgroup>
<!-- and so on -->

This would apply “alternative” to the last two columns.

When span is used in colgroup, you shouldn’t then use col tags.

Caption interlude

A brief and easy accessibility consideration is to apply a caption to the table. The caption element defines the caption and should be used straight after the opening table tag.


<table>
    <strong><caption>Locust mating habits</caption></strong>
<!-- etc. -->

A caption will appear above the table by default, although using the CSS caption-side: bottom will, well, do what you would expect.

The mightier figcaption would be preferable to caption if you are marking up a table as the sole content of a figure element. See the Sectioning page for more.

Headers and Footers

thead, tfoot and tbody allow you to separate the table into header, footer and body, which can be handy when dealing with larger tables.

Whereas thead needs to come first, tfoot can, in fact come before a tbody (and you can have more than one tbody, if it takes your fancy) although browsers will render the tfoot element at the bottom of the table.


<table>
    <strong><thead></strong>
        <tr>
            <td>Header 1</td>
            <td>Header 2</td>
            <td>Header 3</td>
        </tr>
    <strong></thead></strong>
    <strong><tfoot></strong>
        <tr>
            <td>Footer 1</td>
            <td>Footer 2</td>
            <td>Footer 3</td>
        </tr>
    <strong></tfoot></strong>
    <strong><tbody></strong>
        <tr>
            <td>Cell 1</td>
            <td>Cell 2</td>
            <td>Cell 3</td>
        </tr>
        <!-- etc. -->
    <strong></tbody></strong>
</table>

Accessible Links

There are a number of ways links — the absolutely fundamentally most important interactive element of websites — can be made more accessible to those people with disabilities.

Tabbing

Users who do not or cannot use pointing devices can tab through links and, as such, links should be in a logical tabbing order. The tabindex attribute allows you to define this order although if the HTML is linear, as it should be, a logical tabbing order should automatically fall into place.


<ul>
    <li><a href="here.html" <strong>tabindex="1"</strong>>Here</a></li>
    <li><a href="there.html" <strong>tabindex="3"</strong>>There</a></li>
    <li><a href="limbo.html" <strong>tabindex="2"</strong>>Limbo</a></li>
</ul>

In this example (which is used purely as a demonstration – it would be quite dumb, practically speaking), tabbing would jump from “Here” to “Limbo” to “There”.

The good bit of link-accessibility advice is to write good link text. Have the words the a tags wrap around explain where the link will take the user. If someone is using a screen reader, having the links read out to them as they tab between them, the user will then know what they’re letting themselves in for if they select a link. “Click here” or random words aren’t especially helpful…

If you have a link that isn’t self-descriptive or the link destination could benefit from being explained in more detail, you can add information to a link using the title attribute.


<p>I'm really bad at writing link text. <a href="inept.html" <strong>title="Why am I writing link text."</strong>>Click here</a> to find out more.</p>

Another tip: Don’t have links open something in a new window or tab. It’s precious to think your page is important enough to stay alive while a user visits elsewhere anyway. We all know how to use the back button. We know how to close windows and tabs, too, but if you can’t see that that’s what has happened…

Accesskeys

Access keys allow easier navigation by assigning a keyboard shortcut to a link (which will usually gain focus when the user presses “Alt” or “Ctrl” + the access key).


<a href="somepage.html" <strong>accesskey="s"</strong>>Some page</a>

For users who do not use pointing devices, this can be a quick way to navigate. The trouble is that there the user may not know what they are unless they are explicitly stated although some assistive software will tell the user what these are.

Skipping HTML

To aid tabbing, you can supply links that allow users to jump over chunks of your web page. You might want to allow someone to jump over a plethora of navigation links, for example, so they can just read a page’s main content rather than cycle through all of the links:


<header>
    <h1>The Heading</h1>
    <a href="#content">Skip to content</a>
</header> 

<nav>
    <!--loads of navigation stuff -->
</nav>

<section id="content">
    <!--lovely content -->
</section>

You probably won’t want this link to be displayed visually – it’s a peculiar link to see for abled-bodied users and screen reader users won’t need to see it (it will be read out). So you can use CSS to render it invisible but it could also be beneficial to those with motor disabilities so you might also want to consider making it visible when it has focus from being tabbed to using the :focus CSS pseudo class.

Accessible Forms

Forms aren’t the easiest of things to use for people with disabilities. Navigating around a page with written content is one thing, hopping between form fields and inputting information is another. Because of this, adding several elements to the form is a good idea.

Labels

Each form field should have its own explicit label. The label tag sorts this out, with a for attribute that associates it to a form element:


<form>
    <strong><label for="yourName">Your Name</label></strong>
    <input name="yourName" id="yourName">
    <!-- etc. -->

Labels have the added bonus of visual browsers rendering the labels themselves clickable, putting the focus on the associated form field.

Both name and id attributs are typically required; the name for the form to handle that field and the id for the label to associate it to.

Field sets and legends

You can group fields, for example name (first, last, middle, title etc.) or address (line 1, line 2, county, country, postal code, country etc.) using the fieldset tag.

Within the field set, you can set a caption with the legend tag.


<form action="somescript.php" >
    <strong><fieldset></strong>
        <strong><legend>Name</legend></strong>
        <p>First name <input name="firstName"></p>
        <p>Last name <input name="lastName"></p>
    <strong></fieldset></strong>
    <strong><fieldset></strong>
        <strong><legend>Address</legend></strong>
        <p>Address <textarea name="address"></textarea></p>
        <p>Postal code <input name="postcode"></p>
    <strong></fieldset></strong>
    <!-- etc. -->

Most browsers tend to represent field sets with a border surrounding them and the legend caption breaking the left of the top border by default. You can, of course, change this with CSS if you wish.

Option groups

The optgroup element groups options in a select box. It requires a label attribute, the value of which is displayed as a non-selectable pseudo-heading preceding that group in the drop-down list of visual browsers.


<select name="country">
    <strong><optgroup label="Africa"></strong>
        <option value="gam">Gambia</option>
        <option value="mad">Madagascar</option>
        <option value="nam">Namibia</option>
    <strong></optgroup></strong>
    <strong><optgroup label="Europe"></strong>
        <option value="fra">France</option>
        <option value="rus">Russia</option>
        <option value="uk">UK</option>
    <strong></optgroup></strong>
    <strong><optgroup label="North America"></strong>
        <option value="can">Canada</option>
        <option value="mex">Mexico</option>
        <option value="usa">USA</option>
    <strong></optgroup></strong>
</select>

Like links, form fields (and field sets) need to be navigated to without the use of a pointing device, such as a mouse. The same methods used in links to make this task easier can be used on form elements — tab stops and access keys.

The accesskey and tabindex attributes can be added to the individual form tags such as input and also to legend tags.


<input name="firstName" accesskey="f" tabindex="1">

HTML5 Forms Pt. 1: Input Types

HTML5 greatly advances form controls, with numerous additional input types, several new attributes, and a handful of extra elements.

Additional input types

Basic form fields were created using the input element, including text, password, checkbox, radio, and submit, which have already been covered in the HTML Beginner section. These types have been extended in HTML5 to accommodate more specific fields:

Used for a search query text box, this performs exactly as a standard text input should.


<input type="search" name="search">

The main intention of the inclusion of this input type in the HTML5 specification is one of style. As well as making your HTML clearer, you can also target this element with a CSS attribute selector:


input[type=search] { background: url(magnifyingglass.png) right no-repeat) }

Telephone, URL, and email addresses

Other “special” text input types include tel, for telephone numbers, url, for web addresses, and email, for email addresses.


<input type="tel" name="telephone_number">
<input type="url" name="web_address">
<input type="email" name="email_address">

You can use the :valid and :invalid CSS3 pseudo classes to style these fields depending on whether their content is considered valid.


input[type=email]:valid { background: green }
input[type=email]:invalid { background: red }

This example will paint an email field’s background green if the entered text is recognized as an email address (such as “[email protected]”) or red if it isn’t (if the user were to type “sausages?”, for example).

Numbers and ranges

A simple text box that also allows a user to directly type in a number, or cycle through numbers (usually using an up and down arrow to the side of the field), can be achieved with type="number". A further step attribute can be added to specify how much is added or subtracted from the number with each increment.

If you also want the number to have a minimum or maximum value, you can further use the min and max attributes.


<input type="number" name="quantity" step="2" min="20" max="30">

Once again, if this is supported, the user will be able either to type directly into the field or, if using the arrows, cycle between 20 and 30, two units at a time.

You can use the :valid and :invalid pseudo classes in relation to this, too. If the user were to type “12”, for example, that would be invalid, because it isn’t between 20 and 30. If they typed “23” that would also be invalid because it isn’t a multiple of 2.

An alternative to the digits-in-a-text-box approach can be achieved using type="range". By default, this should be displayed as a horizontal bar with a slider in the middle of it. The user can then adjust the slider left and right, the far left resulting in a value of “0” and the far right a value of “100”. This range can be adjusted using the min and max attributes.


<input type="range" name="temperature" min="15" max="25" step="0.5" value="18.5">

Dates and times

There are several input types for dates and times:

If supported (they aren’t, widely, and they are also inconsistent between browsers), these will prompt the user to enter a date or time in a specific format, either by directly typing it in, cycling through one week/day/hour/minute/etc. at a time, or by selecting from a dropdown calendar.

step, min, and max attributes can be used with dates and times, too, as can the CSS pseudo classes to style according to validity.

Color

Finally, type="color" is designed to allow a user to select a color, sending a six-digit hex code as its value.


<input name="color" type="color" value="#ff8800">

HTML5 Forms Pt. 2: Attributes and Data Lists

Continuing from HTML5 Forms Pt. 1, in addition to the multitude of fresh new input types, there are also additional form-specific attributes at your disposal as well as data lists, a sort of text/select hybrid.

More attributes

As well as those attributes mentioned, both here and in earlier guides, there is a handful of additional attributes:

Placeholder text

The placeholder attribute can be used with text input fields (and their text-like cousins, such as type="email" and type="number") as well as textarea elements. It is intended as a hint, rather than a label, for which a label element should still be used.


<label for="email_address">Email address</label>
<input type="email" <em>placeholder="[email protected]"</em> name="email_address" id="email_address">

Autofocus

You might want focus to land on a form field when a page loads. If you think of a search engine, for example, when you land on its home page you don’t normally need to click on the search box to start typing – you can do so straight away because it already has focus. The autofocus attribute is a quick way to achieve this effect.


<input name="query" autofocus>

Data lists

A data list takes the form of a list of suggestions that accompanies a text field:


<input name="country" list="country_name">
<datalist id="country_name">
    <option value="Afghanistan">
    <option value="Albania">
    <option value="Algeria">
    <option value="Andorra">
    <option value="Armenia">
    <option value="Australia">
    <option value="Austria">
    <option value="Azerbaijan">
    <!-- etc. -->
</datalist>

The value of the list attribute in the input element (which could be any of the text-like input types) binds it to a datalist element with the corresponding ID (“country_name”, in this example). As a user types in the text field, if what they type matches the start of anything in the data list, those matches will be shown underneath the text field as suggestions. So, here, if “A” is typed, the 8 countries beginning with “a” are displayed. If “L” is typed after “A”, the list of suggestions will reduce to just “Albania” and “Algeria”, and so on. The data sent when the form is submitted will be whatever is in the text field – it could be something selected from the list or it could be something completely different, inputted by the user.

The good news is that many of the features outlined in these two HTML 5 Forms pages degrade gracefully. Those browsers that don’t support data lists still maintain the text box; unrecognised input types revert to text inputs, so you can use the likes of search, tel, and url as long as you aren’t relying on their special features; placeholder text simply won’t appear so as long as it isn’t essential, go for it.

User Name Password


<html>
<head>
	<meta charset="utf-8">
	<title>Text and password inputs</title>
	<style>
		body {
			font: 100% arial, helvetica, sans-serif;
		}

		fieldset {
			padding: 0 1em 1em 1em;
		}

		legend {
			padding: 1em;
		}
	</style>
</head>
<body>
	<form action="someplace.php">
		<fieldset>
			<legend>Text and Password</legend>
			<label for="username">Username:</label>
			<input name="username" id="username" value="Some Text">
			<label for="password">Password:</label>
			<input type="password" name="password" id="password" value="Password">
		</fieldset>
	</form>

	
	
</body>
</html>

Checkboxes and Radio Buttons

!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Checkbox and radio inputs</title>
	<style>
		body {
			font: 100% arial, helvetica, sans-serif;
		}

		fieldset {
			padding: 0 1em 1em 1em;
		}

		legend {
			padding: 1em;
		}

		label {
			float: left;
			width: 6em;
		}
	</style>
</head>
<body>
	<form action="someplace.php">
		<fieldset>
			<legend>Films you like</legend>
			<div>
				<label for="drama">Drama</label>
				<input type="checkbox" name="drama" id="drama" value="drama">
			</div>
			<div>
				<label for="action">Action</label>
				<input type="checkbox" name="action" id="action" value="action">
			</div>
			<div>
				<label for="comedy">Comedy</label>
				<input type="checkbox" name="comedy" id="comedy" value="comedy">
			</div>
			<div>
				<label for="horror">Horror</label>
				<input type="checkbox" name="horror" id="horror" value="horror">
			</div>
			<div>
				<label for="scifi">Sci-fi</label>
				<input type="checkbox" name="scifi" id="scifi" value="scifi">
			</div>
		</fieldset>

		<fieldset>
			<legend>Your age</legend>
			<div>
				<label for="lt20">19 or under</label>
				<input type="radio" name="age" id="lt20" value="lt20">
			</div>
			<div>
				<label for="20to39">20 to 39</label>
				<input type="radio" name="age" id="20to39" value="20to39">
			</div>
			<div>
				<label for="40to59">40 to 59</label>
				<input type="radio" name="age" id="40to59" value="40to59">
			</div>
			<div>
				<label for="gt59">60 or over</label>
				<input type="radio" name="age" id="gt59" value="gt59">
			</div>
		</fieldset>
	</form>

	
</body>
</html>

File Submissions


<html>
<head>
	<meta charset="utf-8">
	<title>File inputs</title>
	<style>
		body {
			font: 100% arial, helvetica, sans-serif;
		}
	
		fieldset {
			padding: 0 1em 1em 1em;
		}
	
		legend {
			padding: 1em;
		}
	</style>
</head>
<body>
	<form action="someplace.php" method="post" enctype="multipart/form-data">
		<fieldset>
			<legend>Upload file</legend>
			<label for="uploadfile">File name: </label>
			<input type="file" name="uploadfile" id="uploadfile">
		</fieldset>
	</form>


</body>
</html>

Text Area


<html>
<head>
	<meta charset="utf-8">
	<title>Text areas</title>
	<style>
		body {
			font: 100% arial, helvetica, sans-serif;
		}

		fieldset {
			padding: 0 1em 1em 1em;
		}

		legend {
			padding: 1em;
		}

		label {
			float: left;
			clear: left;
			width: 7em;
		}
	</style>
</head>
<body>
	<form action="someplace.php">
		<fieldset>
			<legend>Contact us</legend>
			<div>
				<label for="name">Name: </label>
				<input name="name" id="name">
			</div>
			<div>
				<label for="email">Email address: </label>
				<input name="email" id="email">
			</div>
			<div>
				<label for="message">Message: </label>
				<textarea rows="10" cols="40" name="message" id="message"></textarea>
			</div>
		</fieldset>
	</form>


</body>
</html>

Select Box


<html>
<head>
	<meta charset="utf-8">
	<title>Select menus</title>
	<style>
		body {
			font: 100% arial, helvetica, sans-serif;
		}

		fieldset {
			padding: 0 1em 1em 1em;
		}

		legend {
			padding: 1em;
		}
	</style>
</head>
<body>
	<form action="someplace.php">
		<fieldset>
			<legend>Favourite book</legend>
			<label for="book">Name: </label>
			<select name="book" id="book">
				<option>The Trial</option>
				<option>The Outsider</option>
				<option>Things Fall Apart</option>
				<option>Animal Farm</option>
			</select>
		</fieldset>
	</form>


</body>
</html>

Select: Optgroup Element


<html>
<head>
	<meta charset="utf-8">
	<title>Select menus: option groups</title>
	<style>
		body {
			font: 100% arial, helvetica, sans-serif;
		}

		fieldset {
			padding: 0 1em 1em 1em;
		}

		legend {
			padding: 1em;
		}
	</style>
</head>
<body>
	<form action="someplace.php">
		<fieldset>
			<legend>Favourite book</legend>
			<label for="book">Name: </label>
			<select name="book" id="book">
				<optgroup label="Camus">
					<option>The Outsider</option>
					<option>The Rebel</option>
					<option>The Plague</option>
				</optgroup>
				<optgroup label="Orwell">
					<option>Animal Farm</option>
					<option>Nineteen Eighty-Four</option>
					<option>Down and Out in Paris and London</option>
				</optgroup>
			</select>
		</fieldset>
	</form>

</body>
</html>

Multiple Selection Boxes

!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Select menus: multiple selections</title>
	<style>
		body {
			font: 100% arial, helvetica, sans-serif;
		}

		fieldset {
			padding: 0 1em 1em 1em;
		}

		legend {
			padding: 1em;
		}
	</style>
</head>
<body>
	<form action="someplace.php">
		<fieldset>
			<legend>Favourite book</legend>
			<label for="book">Name: </label>
			<select name="book" id="book" size="5" multiple="multiple">
				<option>The Outsider</option>
				<option>The Rebel</option>
				<option>The Plague</option>
				<option>Things Fall Apart</option>
				<option>Animal Farm</option>
				<option>Nineteen Eighty-Four</option>
				<option>Down and Out in Paris and London</option>
			</select>
		</fieldset>
	</form>

	<!-- Link back to HTML Dog: -->
	<p><a href="http://www.htmldog.com/examples/"><img src="http://www.htmldog.com/badge1.gif" alt="HTML Dog"></a></p>
</body>
</html>

Embedded Content: Video, Audio, and Canvas

HTML5 introduces a swathe of new tags to accommodate the Web’s increasingly interactive and multimedia nature. While there have been numerous ways to embed video, audio, and dynamic imagery, the new web standard attempts to make this easier, more consistent, and more reliable.

Video


<video src="kitties.mp4" controls></video>

This will embed a video, complete with controls, in browsers that support the HTML5 video tag and the video content type.

While HTML5 is pushing for a standard framework to play media, the media itself is not standardised across browsers. In practice, this means that it is unlikely all visitors will be able to experience your video (or audio) file. Some support WebM video, for example, while others support MPEG. Don’t lose too much sleep over this, though — see “Alternative content”, below.

The controls attribute is optional but if you don’t want it – if you really want to take control away from the user – you can just slap in an autoplay attribute:


<video src="kitties.mp4" autoplay></video>

This will play the video on page load, won’t display any controls, and will most likely annoy your visitors. Of course, you could, if you were kind, put in both the controls and autoplay attributes.

Other basic attributes at your disposal include width, height, loop, and muted.


<video src="kitties.mp4" width="300" height="200" loop muted autoplay controls></video>

If you insist on using autoplay, bringing muted (and controls) to the party as well is a nice gesture and is a convention that many sites employ. If you have a video in an aside, for example, it can begin playing but the user can then opt to follow it by de-muting the video via the controls, if they choose, decreasing the likelihood of irritation.

Poster

You can specify a placeholder image, which will be displayed before the video is played, with the poster attribute.


<video src="kitties.mp4" poster="fluffy.jpg" controls></video>

The specified image will stretch or shrink to fit the dimensions of the video, regardless of the original size of the image.

Fall-back content

So, yes, there is an opening and closing tag. Whatever could go in between them? Why, fall-back content: content that is displayed if the browser doesn’t understand the video element. That could be a few words, a chunk of HTML, or a “really funny” and “highly original” Lolcats image.


<video src="kitties.mp4" controls>
    <img src="hahahaha.jpg" alt="Hilarious cat and caption saying 'soz'.">
</video>

Alternative content

As already noted, it’s not only compatibility with the tag we need to worry about, but also compatibility with the source video itself. Luckily, more than one video source file can be offered up with the source element along with indications of the requirements of the file in the value of the type attribute. The browser will then take the first one it’s happy with.


<video controls>
    <source src="kitties.mp4" type="video/mp4; codecs='avc1, mp4a'">
    <source src="kitties.webm" type="video/webm; codecs='vp8.0, vorbis'">
    <p>Browser no likey HTML 5.</p>
</video>

Here, a browser should figure out if it can handle the “video/mp4” MIME type and if it has the stated codec to decipher it. If it doesn’t, it should move on to the next and try again with the details set out in the second source element.

Audio

Applying audio is just like applying video. Using the audio tag, the structure is the same as using video and the attributes src, controls, autoplay and loop can all be used in the same way.


<audio src="meow_mix.mp3" controls>
    Your stupid browser doesn't support HTML 5 audio.
</audio>

Alternative content can also be defined in exactly the same way as with the video and source tags.

Much greater control can be exercised over video and audio using JavaScript, with the ability to manipulate aspects of playback and user controls in more detail.

Canvas

A major addition to HTML5 is the canvas element. It is designed to provide a canvas onto which JavaScript can be used to paint all manner of dynamic images such as graphs, animated sprites, or daft cat pictures.


<canvas id="wittykitty" width="800" height="450">
    <!-- Fall-back content here, just like with video and audio -->
</canvas>

From: https://www.htmldog.com/

CSS

CSS, or Cascading Styles Sheets, is a way to style and present HTML. Whereas the HTML is the meaning or content, the style sheet is the presentation of that document.

Styles have a format of ‘property: value’ and most properties can be applied to most HTML tags.


Applying CSS

There are three ways to apply CSS to HTML: Inline, internal, and external.

Inline

Inline styles are plonked straight into the HTML tags using the style attribute.

They look something like this:

<p style="color: red">text</p>

This will make that specific paragraph red.

But, if you remember, the best-practice approach is that the HTML should be a stand-alone, presentation free document, and so in-line styles should be avoided wherever possible.


External

External styles are used for the whole, multiple-page website. There is a separate CSS file, which will simply look something like:

p {
    color: red;
}

a {
    color: blue;
}

If this file is saved as “style.css” in a folder called “css” in the same directory as your HTML page then it can be linked to in the HTML like this:


<html>
<head>
    <title>CSS Example</title>
    <link rel="stylesheet" href="css/style.css">
...

Apply!

To get the most from this guide, it would be a good idea to try out the code as we go along, so start a fresh new file with your text-editor and save the blank document as “style.css” in the same directory as your HTML file.


Selectors, Properties, and Values

Whereas HTML has tags, CSS has selectors. Selectors are the names given to styles in internal and external style sheets. We will be concentrating on HTML selectors, which are simply the names of HTML tags and are used to change the style of a specific type of element.

For each selector there are “properties” inside curly brackets, which take the form of words such as color, font-weight or background-color.

A value is given to the property following a colon (NOT an “equals” sign). Semi-colons are used to separate the properties.

body {
    font-size: 14px;
    color: navy;
}

This will apply the given values to the font-size and <strong>color</strong> properties to the body selector.

So basically, when this is applied to an HTML document, text between the body tags (which is the content of the whole window) will be 14 pixels in size and navy in color.

Lengths and Percentages

There are many property-specific units for values used in CSS, but there are some general units that are used by several properties, and it is worth familiarizing yourself with these before continuing.

Other units include pc (picas), cm (centimeters), mm (millimeters) and in (inches).

You do not need to state a unit when a value is zero. For example, if you wanted to specify no border, it would be border: 0.

“px” in this case, doesn’t necessarily mean pixels – the little squares that make up a computer’s display – all of the time. Modern browsers allow users to zoom in and out of a page so that, even if you specify, or height: 200px, for example, although these will be the genuine specified size on a non-zoomed browser, they will still increase and decrease in size with the user’s preference.

From: https://www.htmldog.com/


Colors

CSS brings 16,777,216 colors to your disposal. They can take the form of a name, an RGB (red/green/blue) value or a hex code.

The following values, to specify full-on as red-as-red-can-be, all produce the same result:

Predefined color names include aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. transparent is also a valid value.

With the possible exception of black and white, color names have limited use in modern, well-designed web sites because they are so specific and limiting.

The three values in the RGB value are from 0 to 255, 0 being the lowest level (no red, for example), 255 being the highest level (full red, for example). These values can also be a percentage.

Hexadecimal is a base-16 number system. We are generally used to the decimal number system (base-10, from 0 to 9), but hexadecimal has 16 digits, from 0 to f.

The hex number is prefixed with a hash character (#) and can be three or six digits long. The three-digit version is a compressed version of the six-digit (#ff0000 becomes #f00, #cc9966 becomes #c96, etc.). The three-digit version is easier to decipher (the first digit, like the first value in RGB, is red, the second green and the third blue) but the six-digit version gives you more control over the exact color.


color and background-color

Colors can be applied by using color and background-color

A blue background and yellow text could look like this:

h1 {
    color: yellow;
    background-color: blue;
}

These colors might be a little too harsh, so you could change the code of your CSS file for slightly different shades:

body {
    font-size: 14px;
    color: navy;
}

h1 {
    color: #ffc;
    background-color: #009;
}

Save the CSS file and refresh your browser. You will see the colors of the first heading (the h1 element) have changed to yellow and blue.

You can apply the color and background-color properties to most HTML elements, including body, which will change the colors of the page and everything in it.

Text (Intro & Advanced)

You can alter the size and shape of the text on a web page with a range of properties.

font-family

This is the font itself, such as Times New Roman, Arial, or Verdana.

The user’s browser has to be able to find the font you specify, which, in most cases, means it needs to be on their computer so there is little point in using obscure fonts that are only sitting on your computer. There are a select few “safe” fonts (the most commonly used are Arial, Verdana and Times New Roman), but you can specify more than one font, separated by commas. The purpose of this is that if the user does not have the first font you specify, the browser will go through the list until it finds one it does have. This is useful because different computers sometimes have different fonts installed. So font-family: arial, helvetica, serif, will look for the Arial font first and, if the browser can’t find it, it will search for Helvetica, and then a common serif font.

Note: if the name of a font is more than one word, it should be put in quotation marks, such as font-family: "Times New Roman".

font-size

<strong>font-size</strong> sets the size of the font. Be careful with this — text such as headings should not just be an HTML paragraph (p) in a large font – you should still use headings (h1, h2 etc.) even though, in practice, you could make a paragraph’s font-size larger than a heading (not recommended).

font-weight

<strong>font-weight</strong> states whether the text is bold or not. Most commonly, this is used as font-weight: bold or font-weight: normal but other values are bolder, lighter, 100, 200, 300, 400 (same as normal), 500, 600, 700 (same as bold), 800 or 900.

![](https://image-control-storage.s3.amazonaws.com/2023/03/31160603/weightStyle-1-19.gif)

See the Pen Headings by Nicholas D’Angelo (@ndangelo) on CodePen.

font-style

font-style states whether the text is italic or not. It can be font-style: italic or font-style: normal.

text-decoration

text-decoration states whether the text has got a line running under, over, or through it.

This property is usually used to decorate links and you can specify no underline with text-decoration: none.

text-transform

text-transform will change the case of the text.

So, a few of these things used together might look like this:

body {
    font-family: arial, helvetica, sans-serif;
    font-size: 14px;
}

h1 {
    font-size: 2em;
}

h2 {
    font-size: 1.5em;
}

a {
    text-decoration: none;
}

strong {
    font-style: italic;
    text-transform: uppercase;
}

Text spacing

Before we move on from this introduction to styling text, a quick look at how to space out the text on a page.

![](https://image-control-storage.s3.amazonaws.com/2023/03/31160608/spacingOutText-17.gif)

The letter-spacing and word-spacing properties are for spacing between letters or words. The value can be a length or normal.

The line-height property sets the height of the lines in an element, such as a paragraph, without adjusting the font size. It can be a number (which specifies a multiple of the font size, so “2” will be two times the font size, for example), a length, a percentage, or normal.

The text-align property will align the text inside an element to left, right, center, or justify.

The text-indent property will indent the first line of a paragraph, for example, to a given length or percentage. This style is traditionally used in print, but rarely in digital media such as the web.

p {
    letter-spacing: 0.5em;
    word-spacing: 2em;
    line-height: 1.5;
    text-align: center;
}

See the Pen Text-align, text-indent, word and letter spacing by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Vertical Align by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Text Shadow by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Drop Caps by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Drop caps 2 (Image) by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Pull Quotes One by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Another Pull Quote by Nicholas D’Angelo (@ndangelo) on CodePen.

From: https://www.htmldog.com/

Margins and Padding

margin and padding are the two most commonly used properties for spacing-out elements. A margin is the space outside something, whereas padding is the space inside something.

Change the CSS code for h2 to the following:

h2 {
    font-size: 1.5em;
    <strong>background-color: #ccc;</strong>
    <strong>margin: 20px;</strong>
    <strong>padding: 40px;</strong>
}

This leaves a 20-pixel width space around the secondary header and the header itself is fat from the 40-pixel width padding.

The four sides of an element can also be set individually. margin-top, margin-right, margin-bottom, margin-left, padding-top, padding-right, padding-bottom and padding-left are the self-explanatory properties you can use.

The Box Model

Margins, padding and borders are all part of what’s known as the Box Model. The Box Model works like this: in the middle you have the content area (let’s say an image), surrounding that you have the padding, surrounding that you have the border and surrounding that you have the margin. It can be visually represented like this:

Margin box
Border box
Padding box
Element box

You don’t have to use all of these, but it can be helpful to remember that the box model can be applied to every element on the page.

See the Pen Overflow by Nicholas D’Angelo (@ndangelo) on CodePen.

Borders

Borders can be applied to most HTML elements within the body.

To make a border around an element, all you need is border-style. The values can be solid, dotted, dashed, double, groove, ridge, inset and outset.

![](https://image-control-storage.s3.amazonaws.com/2023/03/31160612/border-style-15.png)

border-width sets the width of the border, most commonly using pixels as a value. There are also properties for border-top-width, border-right-width, border-bottom-width and border-left-width.

Finally, border-color sets the color.

h2 {
    border-style: dashed;
    border-width: 3px;
    border-left-width: 10px;
    border-right-width: 10px;
    border-color: red;
}

This will make a red dashed border around all HTML secondary headers (the h2 element) that is 3 pixels wide on the top and bottom and 10 pixels wide on the left and right (these having over-ridden the 3 pixel wide width of the entire border).

Putting It All Together

The code below covers all of the CSS methods in this section. If you save this as your CSS file and look at the HTML file then you should now understand what each CSS property does and how to apply them.

body {
    font-family: arial, helvetica, sans-serif;
    font-size: 14px;
    color: black;
    background-color: #ffc;
    margin: 20px;
    padding: 0;
}

/* This is a comment, by the way */

p {
    line-height: 21px;
}

h1 {
    color: #ffc;
    background-color: #900;
    font-size: 2em;
    margin: 0;
    margin-bottom: 7px;
    padding: 4px;
    font-style: italic;
    text-align: center;
    letter-spacing: 0.5em;
    border-bottom-style: solid;
    border-bottom-width: 0.5em;
    border-bottom-color: #c00;
}

h2 {
    color: white;
    background-color: #090;
    font-size: 1.5em;
    margin: 0;
    padding: 2px;
    padding-left: 14px;
}

h3 {
    color: #999;
    font-size: 1.25em;
}

img {
    border-style: dashed;
    border-width: 2px;
    border-color: #ccc;
}

a {
    text-decoration: none;
}

strong {
    font-style: italic;
    text-transform: uppercase;
}

li {
    color: #900;
    font-style: italic;
}


/* Table Style are not covered in this class */

/*table {
    background-color: #ccc;
}*/

Assignment

  1. Use the “Putting it all Together” css code above and create a simple HTML page incorporating every CSS element.
  2. If you finish early, incorporate styles that are not within the “Putting it all Together” section. You can do some crazy things! You can use everything you’ve learned in class so far.
  3. Remember to use a separate stylesheet, add “border-box” to your CSS, and lang=”en”.

Border-Borders

See the Pen Border-Borders by Nicholas D’Angelo (@ndangelo) on CodePen.

From: https://www.htmldog.com/

Span and Div

HTML is all about applying meaning to content. Whereas most HTML tags apply meaning (p makes a paragraph, h1 makes a heading etc.), the span and div tags apply no meaning at all. This might sound about as useful as a foam hammer but they are actually used quite extensively in conjunction with CSS.

They are used to group together a chunk of HTML and hook some information onto that chunk, most commonly with the attributes class and id to associate the element with a class or id CSS selector.

The difference between span and div is that a span element is in-line and usually used for a small chunk of HTML inside a line (such as inside a paragraph), whereas a div (division) element is block-line (which is the equivalent to having a line-break before and after it) and used to group larger chunks of code.

<div id="scissors">
    <p>This is <span class="paper">crazy</span></p>
</div>

Class and ID Selectors

For this we look solely at HTML selectors — those that represent an HTML tag.

You can also define your own selectors in the form of class and ID selectors.

The benefit of this is that you can have the same HTML element, but present it differently depending on its class or ID.

In the CSS, a class selector is a name preceded by a full stop (“.”) and an ID selector is a name preceded by a hash character (“#”).

So the CSS might look something like:

<strong>#top</strong> {
    background-color: #ccc;
    padding: 20px
}

<strong>.intro</strong> {
    color: red;
    font-weight: bold;
}

The HTML refers to the CSS by using the attributes id and class. It could look something like this:


<div <strong>id="top"</strong>>

<h1>Chocolate curry</h1>

<p <strong>class="intro"</strong>>This is my recipe for making curry purely with chocolate</p>

<p <strong>class="intro"</strong>>Mmm mm mmmmm</p>

</div>

The difference between an ID and a class is that an ID can be used to identify one element, whereas a class can be used to identify more than one.

You can also apply a selector to a specific HTML element by simply stating the HTML selector first, so p.jam { /* whatever */ } will only be applied to paragraph elements that have the class “jam”.

Grouping and Nesting

Two ways that you can simplify your code — both HTML and CSS — and make it easier to manage.

Grouping

You can give the same properties to a number of selectors without having to repeat them.

For example, if you have something like:


h2 {
    color: red;
}

.thisOtherClass {
    color: red;
}

.yetAnotherClass {
    color: red;
}

You can separate selectors with commas in one line and apply the same properties to them all so, making the above:


<strong>h2, .thisOtherClass, .yetAnotherClass</strong> {
    color: red;
}

Nesting

If the CSS is structured well, there shouldn’t be a need to use many class or ID selectors. This is because you can specify properties to selectors within other selectors.

For example:


#top {
    background-color: #ccc;
    padding: 1em
}

<strong>#top h1</strong> {
    color: #ff0;
}

<strong>#top p</strong> {
    color: red;
    font-weight: bold;
}

This removes the need for classes or IDs on the p and h1 tags if it is applied to HTML that looks something like this:


<div id="top">
    <h1>Chocolate curry</h1>
    <p>This is my recipe for making curry purely with chocolate</p>
    <p>Mmm mm mmmmm</p>
</div>

This is because, by separating selectors with spaces, we are saying “h1 inside ID top is colour #ff0” and “p inside ID top is red and bold”.

This can get quite complicated (because it can go for more than two levels, such as this inside this inside this inside this etc.) and may take a bit of practice.

Pseudo Classes

Pseudo classes are bolted on to selectors to specify a state or relation to the selector. They take the form of selector:pseudo_class { property: value; }, simply with a colon in between the selector and the pseudo class.

Links

link, targeting unvisited links, and visited, targeting, you guessed it, visited links, are the most basic pseudo classes.

The following will apply colors to all links in a page depending on whether the user has visited that page before or not:


a<strong>:link</strong> {
    color: blue;
}

a<strong>:visited</strong> {
    color: purple;
}

Dynamic Pseudo Classes

Also commonly used for links, the dynamic pseudo classes can apply styles when something happens to something.

![](https://image-control-storage.s3.amazonaws.com/2023/03/31160615/rollovers_border-7.png)

focus is most often used on form elements but can be used for links. Although most users will navigate around and between pages using a pointing device such as a mouse those who choose note to, or are unable to do so, such as those with motor disabilities, may navigate using a keyboard or similar device. Links can be jumped between using a tab key and they will gain focus one at a time.


a<strong>:active</strong> {
    color: red;
}

a<strong>:hover</strong> {
    text-decoration: none;
    color: blue;
    background-color: yellow;
}

input<strong>:focus</strong>, textarea<strong>:focus</strong> {
    background: #eee;
}

First Children

Finally (for this article, at least), there is the first-child pseudo class. This will target something only if it is the very first descendant of an element. So, in the following HTML…


<body>
    <p>I’m the body’s first paragraph child. I rule. Obey me.</p>
    <p>I resent you.</p>
...

…if you only want to style the first paragraph, you could use the following CSS:


p<strong>:first-child</strong> {
    font-weight: bold;
    font-size: 40px;
}

From: https://www.htmldog.com/

Shorthand Properties

Some CSS properties allow a string of values, replacing the need for a number of properties. These are represented by values separated by spaces.

Margins and Padding

margin allows you to amalgamate margin-top, margin-right, margin-bottom, and margin-left in the form of property: top right bottom left;

So:


p {
    margin-top: 1px;
    margin-right: 5px;
    margin-bottom: 10px;
    margin-left: 20px;
}

Can be summed up as:


p {
    <strong>margin: 1px 5px 10px 20px;</strong>
}

padding can be used in exactly the same way.

By stating just two values (such as padding: 1em 10em;), the first value will be the top and bottom and the second value will be the right and left.

Borders

border-width can be used in the same way as margin and padding, too. You can also combine border-width, border-color, and border-style with the border property. So:


p {
    border-width: 1px;
    border-color: red;
    border-style: solid;
}

Can be simplified to be:


p {
    <strong>border: 1px red solid;</strong>
}

The width/color/style combination can also be applied to border-top, border-right etc.

Fonts

Font-related properties can also be gathered together with the font property:


p {
    <strong>font: italic bold 12px/2 courier;</strong>
}

This combines font-style, font-weight, font-size, line-height, and font-family.

So, to put it all together, try this code:


p {
    font: 14px/1.5 "Times New Roman", times, serif;
    padding: 30px 10px;
    border: 1px black solid;
    border-width: 1px 5px 5px 1px;
    border-color: red green blue yellow;
    margin: 10px 50px;
}

Background Images

Used in a very different way to the img HTML element, CSS background images are a powerful way to add detailed presentation to a page.


body {
<strong>    background: white url(https://www.ndangelo.com/images/bg.gif) no-repeat top right;</strong>
}

This amalgamates these properties:

Assignment

See the Pen Untitled by Nicholas D’Angelo (@ndangelo) on CodePen.

![](https://image-control-storage.s3.amazonaws.com/2023/03/31160616/background-position-4.png)
A top-right positioned, non-repeating background.

See the Pen Images: background-image by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Background Position 1 by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Background Image Size by Nicholas D’Angelo (@ndangelo) on CodePen.

Specificity

If you have two (or more) conflicting CSS rules that point to the same element, there are some basic rules that a browser follows to determine which one is most specific and therefore wins out.

It may not seem like something that important, and in most cases you won’t come across any conflicts at all, but the larger and more complex your CSS files become, or the more CSS files you start to juggle with, the greater likelihood there is of conflicts arising.

More Specific = Greater Precedence

If the selectors are the same then the last one will always take precedence. For example, if you had:


p { color: red }
p { color: blue }

The text in the box of p elements would be colored blue because that rule came last.

However, you won’t usually have identical selectors with conflicting declarations on purpose (because there’s not much point). Conflicts quite legitimately come up, though, when you have nested selectors.


div p { color: red }
p { color: blue }

In this example it might seem that a p within a div would be colored blue, seeing as a rule to color p boxes blue comes last, but they would actually be colored red due to the specificity of the first selector. Basically, the more specific a selector, the more preference it will be given when it comes to conflicting styles.

Calculating Specificity

The actual specificity of a group of nested selectors takes some calculating. You can give every ID selector (“#whatever”) a value of 100, every class selector (“.whatever”) a value of 10 and every HTML selector (“whatever”) a value of 1. When you add them all up, hey presto, you have a specificity value.

So if all of these examples were used, div p.tree (with a specificity of 12) would win out over div p (with a specificity of 2) and body #content .alternative p would win out over all of them, regardless of the order.

From: https://www.htmldog.com/

Display

A key trick to manipulating HTML elements is understanding that there’s nothing special about how most of them work. Most pages could be made up from just a few tags that can be styled any which way you choose. The browser’s default visual representation of most HTML elements consist of varying font styles, margins, padding and, essentially, display types.

The most fundamental types of display are inline, block and none and they can be manipulated with the display property and the shockingly surprising values inline, block and none.

Inline

inline does just what it says — boxes that are displayed inline follow the flow of a line. Anchor (links) and emphasis are examples of elements that are displayed inline by default.

![](https://image-control-storage.s3.amazonaws.com/2023/03/31160618/displayInline-4.png)
Inline boxes.

The following code, for example, will cause all list items in a list to appear next to each other in one continuous line rather than each one having its own line:


li { <strong>display: inline</strong> }

Block

block makes a box standalone, fitting the entire width of its containing box, with an effective line break before and after it. Block boxes allow greater height, margins, and padding manipulation than inline boxes. Heading and paragraph elements are examples of elements displayed this way by default in browsers.

![](https://image-control-storage.s3.amazonaws.com/2023/03/31160620/displayBlock-4.png)
Block boxes.

The next example will make all links in “nav” large clickable blocks:


#navigation a {
    <strong>display: block;</strong>
    padding: 20px 10px;
}

display: inline-block will keep a box inline but lend the greater formatting flexibility of block boxes, allowing margin to the right and left of the box, for example.

None

none, doesn’t display a box at all, which may sound pretty useless but can be used to good effect with dynamic effects, such as switching extended information on and off at the click of a link, or in alternative stylesheets.

The following code, for example, could be used in a print stylesheet to basically “turn off” the display of elements such as navigation that would be useless in that situation:


#navigation, #related_links { <strong>display: none</strong> }

display: none and visibility: hidden vary in that display: none takes the element’s box completely out of play, whereas visibility: hidden keeps the box and its flow in place without visually representing its contents. For example, if the second paragraph of 3 were set to display: none, the first paragraph would run straight into the third whereas if it were set to visibility: hidden, there would be a gap where the paragraph should be.

See the Pen Block and Inline Block by Nicholas D’Angelo (@ndangelo) on CodePen.

See the Pen Block and inline boxes 3 by Nicholas D’Angelo (@ndangelo) on CodePen.

Page Layout

Layout with CSS is easy. You take a part of your page and put it wherever you choose. You can place these elements absolutely or relative to another element.

Positioning

The position property is used to define whether a box is absolute, relative, static or fixed:

When we talk of absolutely positioned boxes being placed anywhere on the page, they’re still relatively positioned from the edges. And to add another backtrack, the page doesn’t actually have to be the container — a box will be “absolutely” positioned in relation to any non-static positioned containing box. Just ignore that for now, though…

Layout using absolute positioning

You can create a traditional two-column layout with absolute positioning if you have something like the following HTML:


<div id="navigation">
    <ul>
        <li><a href="this.html">This</a></li>
        <li><a href="that.html">That</a></li>
        <li><a href="theOther.html">The Other</a></li>
    </ul>
</div>

<div id="content">
    <h1>Ra ra banjo banjo</h1>
    <p>Welcome to the Ra ra banjo banjo page. Ra ra banjo banjo. Ra ra banjo banjo. Ra ra banjo banjo.</p>
    <p>(Ra ra banjo banjo)</p>
</div>

And if you apply the following CSS:


#navigation {
    <strong>position: absolute;</strong>
    <strong>top: 0;</strong>
    <strong>left: 0;</strong>
    width: 200px;
}

#content {
    margin-left: 200px;
}

You will see that this will set the navigation bar to the left and set the width to 200 pixels. Because the navigation is absolutely positioned, it has nothing to do with the flow of the rest of the page so all that is needed is to set the left margin of the content area to be equal to the width of the navigation bar.


#navigation {
    position: absolute;
    top: 0;
    left: 0;
    width: 200px;
}

#navigation2 {
    position: absolute;
    top: 0;
    right: 0;
    width: 200px;
}

#content {
    margin: 0 200px; /* setting top and bottom margin to 0 and right and left margin to 200px */
}

The only downside to absolutely positioned boxes is that because they live in a world of their own, there is no way of accurately determining where they end. If you were to use the examples above and all of your pages had small navigation bars and large content areas, you would be okay, but, especially when using relative values for widths and sizes, you often have to abandon any hope of placing anything, such as a footer, below these boxes. If you wanted to do such a thing, one way would be to float your chunks, rather than absolutely positioning them.

Floating

Floating a box will shift it to the right or left of a line, with surrounding content flowing around it.

Floating is normally used to shift around smaller chunks within a page, such as pushing a navigation link to the right of a container, but it can also be used with bigger chunks, such as navigation columns.

Using float, you can float: left or float: right.

Working with the same HTML, you could apply the following CSS:


#navigation {
    <strong>float: left;</strong>
    width: 200px;
}

#navigation2 {
    <strong>float: right;</strong>
    width: 200px;
}

#content {
    margin: 0 200px;
}

Then, if you do not want the next box to wrap around the floating objects, you can apply the clear property:

So if, for example, you wanted a footer in your page, you could add a chunk of HTML…


<div id="footer">
    <p>Footer! Hoorah!</p>
</div>

…and then add the following CSS:


#footer {
    <strong>clear: both;</strong>
}

And there you have it. A footer that will appear underneath all columns, regardless of the length of any of them.

This has been a general introduction to positioning and floating, with emphasis on the larger “chunks” of a page, but remember, these methods can be applied to any box within those boxes, too.

Specificity

If you have two (or more) conflicting CSS rules that point to the same element, there are some basic rules that a browser follows to determine which one is most specific and therefore wins out.

It may not seem like something that important, and in most cases you won’t come across any conflicts at all, but the larger and more complex your CSS files become, or the more CSS files you start to juggle with, the greater likelihood there is of conflicts arising.

More Specific = Greater Precedence

If the selectors are the same, the last one will always precede. For example, if you had:


p { color: red }
p { color: blue }

The text in the box of p elements would be colored blue because that rule came last.

However, you won’t usually have identical selectors with conflicting declarations on purpose (because there’s not much point). Conflicts quite legitimately come up, though, when you have nested selectors.


div p { color: red }
p { color: blue }

In this example it might seem that a p within a div would be colored blue, seeing as a rule to color p boxes blue comes last, but they would actually be colored red due to the specificity of the first selector. Basically, the more specific a selector, the more preference it will be given when it comes to conflicting styles.

Calculating Specificity

The actual specificity of a group of nested selectors takes some calculating. You can give every ID selector (“#whatever”) a value of 100, every class selector (“.whatever”) a value of 10 and every HTML selector (“whatever”) a value of 1. When you add them all up, hey presto, you have a specificity value.

So if all of these examples were used, div p.tree (with a specificity of 12) would win out over div p (with a specificity of 2) and body #content .alternative p would win out over all of them, regardless of the order.

From: https://www.htmldog.com/

Media Queries

Media queries are used to target CSS at specific media types and media features. Styles can be applied to print or to screens of a certain size, for example.

Applying media queries

Media queries can be added to a link HTML element:


<link rel="stylesheet" href="this.css" media="<strong>print</strong>">
<!-- applies an external print-only stylesheet -->

<link rel="stylesheet" href="that.css" media="<strong>screen and (max-width: 800px)</strong>">
<!-- applies an external stylesheet to screens up to 800 pixels wide -->

Media queries can also be embedded in stylesheets using an @media rule:


@media <strong>print</strong> {
    body {
        font-family: "Times New Roman", Times, serif;
    }
    /* etc. */
}
/* applies styles to print only */

@media <strong>screen and (max-width: 800px)</strong> {
    body {
        padding: 0;
    }
    /* etc. */
}
/* applies styles to screens up to 800 pixels wide */

@import can also be used (@import url(this.css) print, for example).

Media types

screen and print are the most common media types. all can also be used and is the default state of a media query. Others, with patchy support, are braille, embossed, handheld, projection, speech, tty, and tv.

Media features

| Feature | Description | Possible values | |---|---|---| | `width``min-width``max-width` | Display area width. | \[length\], eg. `800px` | | `height``min-height``max-height` | Display area height. | \[length\], eg. `20em` | | `device-width``min-device-width``max-device-width` | Screen width. | \[length\], eg. `2in` | | `device-height``min-device-height``max-device-height` | Screen height. | \[length\], eg. `10cm` | | `orientation` | Portrait (when height is greater than or equal to width) or landscape (when width is greater than height). | `portrait``landscape` | | `aspect-ratio``min-aspect-ratio``max-aspect-ratio` | The ratio of the value of `width` to the value of `height`. | \[ratio\], eg. `2/1` | | `device-aspect-ratio``min-device-aspect-ratio``max-device-aspect-ratio` | The ratio of the value of `device-width` to the value of `device-height`. | \[ratio\], eg. `16/9` | | `color``min-color``max-color` | The number of bits per color component of a screen. | \[integer\] `0` indicates a device is not color. `color` without a value is the equivalent of `min-color: 1` (device is color). | | `color-index``min-color-index``max-color-index` | The number of entries in a device’s color lookup table. | \[integer\] `0` indicates a device does not use a color lookup table. `color-index` without a value is the equivalent of `min-color-index: 1` (device uses a color lookup table). | | `monochrome``min-monochrome``max-monochrome` | The number of bits per pixel on a grayscale device. | \[integer\] `0` indicates a device is not grayscale. `monochrome` without a value is the equivalent of `min-monochrome: 1` (device is grayscale). | | `resolution``min-resolution``max-resolution` | A device’s pixel density. | \[resolution\], eg. `300dpi` | | `scan` | Used with `tv` media type. The scanning process of a device. | `progressive``interlace` | | `grid` | If a device is grid (such as a teletype-like terminal) or bitmap. | \[integer\] `0` indicates a device is not grid. `grid` without a value is the equivalent of `grid: 1` (device is grid). |

Media features and their values should be contained inside parentheses, such as (min-device-aspect-ratio: 16/9) or (color).

Combining media queries

Logical OR: comma-separated list

A comma-separated list will apply styles to multiple media queries.


@media screen, projection {
    /* CSS applied if device is screen OR projection */
}

Logical AND: and

The and keyword will combine media queries.


@media print and (min-resolution: 150dpi) {
    /* CSS applied if device is print AND resolution is at least 150dpi */
}

Logical NOT: not

The not keyword will exclude media queries.


@media not screen {
    /* CSS applied if device is NOT screen */
}

Pseudo Elements

Pseudo elements suck on to selectors much like pseudo classes, taking the form of selector:pseudoelement { property: value; }. There are four of the suckers.

First Letters and First Lines

The first-letter pseudo element applies to the first letter inside a box and first-line to the top-most displayed line in a box.

![](https://image-control-storage.s3.amazonaws.com/2023/03/01160042/firstLetterFirstLine.png)
Targeting the first letter and first line of a paragraph with pseudo elements.

As an example, you could create drop caps and a bold first-line for paragraphs with something like this:


p {
    font-size: 12px;
}

<strong>p:first-letter</strong> {
    font-size: 24px;
    float: left;
}

<strong>p:first-line</strong> {
    font-weight: bold;
}

The CSS 3 specs suggest pseudo elements should include two colons, so p::first-line as opposed to p:first-line. This is to differentiate them with pseudo classes. Aiming for backwards-compatibility (whereby older web pages will still work in new browsers), browsers will still behave if they come across the single colon approach and this remains the best approach in most circumstances due to some older browsers not recognizing the double colon.

Before and After Content

The before and after pseudo elements are used in conjunction with the content property to place content either side of a box without touching the HTML.

What?! Content in my CSS?! But I thought HTML was for content!

Well, it is. So use sparingly. Look at it like this: You are borrowing content to use solely as presentation, such as using “!” because it looks pretty. Not because you actually want to exclaim anything.

The value of the content property can be open-quote, close-quote, any string enclosed in quotation marks, or any image, using url(imagename).


blockquote:before {
    content: open-quote;
}

blockquote:after {
    content: close-quote;
}

li:before {
    content: "POW! ";
}

p:before {
    content: url(images/jam.jpg);
}

The content property effectively creates another box to play with so you can also add styles to the “presentational content”:


li:before {
    content: "POW! ";
    background: red;
    color: #fc0;
}

End of Intermediate CSS Tutorial

From: https://www.htmldog.com/


Code Snippets

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>

<script>
  $(function() {
    $("a[href*=#]:not([href=#])").click(function() {
      if (
        location.pathname.replace(/^//, "") ==
        this.pathname.replace(/^//, "") &&
        location.hostname == this.hostname
      ) {
        var target = $(this.hash);
        target = target.length ? target : $("[name=" + this.hash.slice(1) + "]");
        if (target.length) {
          $("html,body").animate({
              scrollTop: target.offset().top
            },
            1000
          );
          return false;
        }
      }
    });
  });
</script>

Inertia Anchor Link Code:

End of Intermediate Tutorial

Rounded Corners

Rounded corners used to be the stuff of constricting solid background images or, for flexible boxes, numerous background images, one per-corner, slapped on multiple nested div elements. Argh, ugly. Well, not any longer. Now, with simple CSS, you can lavish your designs with more curves than Marilyn Monroe.

Border radius?

Yeah. Border radius. Fear not, though — you don’t have to have borders. The border-radius property can be used to add a corner to each corner of a box.


#marilyn {
    background: #fff;
    width: 100px;
    height: 100px;
    <strong>border-radius: 20px;</strong>
}

And there you have it. Rounded corners, see? Well, you will if you’ve got a sensible browser (see note below).

![](https://image-control-storage.s3.amazonaws.com/2023/03/06131053/border-radius-1.png)
Corners are cut around the corresponding quarters of a circle (or ellipse) with the specified radius.

Of course, if you do want a border…


#ok_a_border_then {
    border: 5px solid #8b2;
    width: 100px;
    height: 100px;
    <strong>border-radius: 5px;</strong>
}

Multiple values

border-top-left-radius, border-top-right-radius, border-bottom-right-radius, and border-bottom-left-radius can also be used to target specific corners.

Ever so slightly less horribly wordy, you can also define all corner radii (what a great word) individually with a space-separated list of values, working clockwise from top-left, just like other shorthand properties:


#monroe {
    background: #fff;
    width: 100px;
    height: 100px;
    <strong>border-radius: 6px 12px 18px 24px;</strong>
}

![](https://image-control-storage.s3.amazonaws.com/2023/03/06131054/border-radius_multiple.png)
Multiple-value border-radius.

By using two values instead of four you target top-left and bottom-right with the first length (or percentage) and top-right + bottom-left with the second. Three values? Top-left, then top-right + bottom-left, then bottom-right.

Ellipses

Are circles a bit too square for you? You can specify different horizontal and vertical radiiii by splitting values with a “/”.


#nanoo {
        background: #fff;
        width: 100px;
        height: 150px;
        <strong>border-radius: 50px/100px;</strong>
        border-bottom-left-radius: 50px;
        border-bottom-right-radius: 50px;
}

![](https://image-control-storage.s3.amazonaws.com/2023/03/06131055/border-radius_nanoo.png)
Nanoo.

Shadows

You can make parts of your page “pop” by applying shadows to boxes and text.

Box Shadows

box-shadow is the standard CSS property to get you going and it can have a value comprising several parts:


box-shadow: 5px 5px 3px 1px #999

Inner shadows

You can also apply shadows to the inside of a box by adding “inset” to the list:


box-shadow: inset 0 0 7px 5px #ddd;

![](https://image-control-storage.s3.amazonaws.com/2023/03/11120502/boxshadow-1-2.png)
A basic drop-shadow and an inner-shadow.

Text Shadows

box-shadow, as its name implies, only has eyes for boxes. Fickle beast. But you can also apply shadows to the outline of text with text-shadow:


text-shadow: -2px 2px 2px #999;

Similarly to box-shadow:

Note that there is no spread distance or inset option for text-shadow.

text-shadow has taken a little bit longer for browsers to figure out. Internet Explorer 9 and below won’t understand it so we suggest only using it in non-critical situations.

Universal, Child, and Adjacent Selectors

In earlier tutorials, we have covered HTML selectors, Class and ID selectors, and how to combine selectors to target specific element boxes. Using three itty-bitty characters, you can further pinpoint an element, reducing the need to bloat your HTML with class and ID attributes.

Universal selectors

Using an asterisk (“ * ”), you can target everything. You can use it by itself to set global styles for a page, or as a descendant of a selector to set styles of everything within something.

The following, for example, will set the margin and padding on everything in a page to zero and everything within an element with the ID “contact” to be displayed as a block:


<strong>*</strong> {
    margin: 0;
    padding: 0;
}

<strong>#contact *</strong> {
    display: block;
}

Using a standalone universal selector is commonly used to “reset” many of a browser’s default styles. Setting a margin to zero, for example, will kill all spacing around paragraphs, headings and blockquotes.

Child selectors

A greater-than symbol (“>”) can be used to specify something that is a child of something else, that is, something immediately nested within something.

So, with this HTML…


<ul id="genus_examples">
    <li>Cats
        <ul>
            <li>Panthera</li>
            <li>Felis</li>
            <li>Neofelis</li>
        </ul>
    </li>
    <li>Apes
        <ul>
            <li>Pongo</li>
            <li>Pan</li>
            <li>Homo</li>
        </ul>
    </li>
</ul>

…and the following CSS…


<strong>#genus_examples > li</strong> { border: 1px solid red }

…a red border would be drawn around “Cats” and “Apes” only, rather than around every single list item (which would be the case with #genus_examples li { border: 1px solid red }). This is because the likes of “Panthera” and “Felis” are grandchildren of “genus_examples”, not children.

Adjacent selectors

A plus sign (“+”) is used to target an adjacent sibling of an element, essentially, something immediately following something.

With the following HTML:


<h1>Clouded leopards</h1>
<p>Clouded leopards are cats that belong to the genus Neofelis.</p>
<p>There are two extant species: Neofelis nebulosa and Neofelis diardi.</p>

…and CSS…


<strong>h1 + p</strong> { font-weight: bold }

Only the first paragraph, that follows the heading, will be bolded.

A further, CSS 3, “general sibling” selector uses a tilde (“~”) and will match an element following another regardless of its immediacy. So, in the above example, h1 ~ p { font-weight: bold } will style all paragraphs after the top-level heading but if there were any ps preceding the h1, these would not be affected.

Advanced Colors

We already know that colors can be defined by name, RGB, or hex values, but CSS 3 also allows you to paint away with HSL — hue, saturation, and lightness — as well as stipulating transparency.

There are no super special properties at play here — HSL and RGBa (the “a” standing for “alpha”, as in “alpha transparency”) can be applied to any property that has a color value, such as color, background-color, border-color or box-shadow, to name a mere handful.

Alpha transparency

RGBa opens up an exciting new dimension to web design, allowing you to set the transparency of a box or text. If you wanted a smidgen of a snazzy background image to peep through a heading, for example, you might use something like this:


h1 {
    padding: 50px;
    background-image: url(snazzy.jpg);
    <strong>color: rgba(0,0,0,0.8);</strong>
}

A standard value of rgb(0,0,0) would set the heading to pure black but that fourth value, in rgba, sets the level of transparency, “1” being completely opaque, “0” being completely transparent. So rgba(0,0,0,0.8) is saying red=“0”, green=“0”, blue=“0”, alpha=“0.8”, which, all together, makes it 80% black.

This doesn’t only apply to text, of course, you could apply a transparent background color to an entire box, a transparent box shadow… anywhere where you can use rgb, you can used rgba.

Hue, saturation, and lightness

Color names aside, web colors have always been red-green-blue biased, be that through hex codes or explicit RBG (or RGBa). Although mildly less straightforward (especially if your brain is trained to break down colors into red, green and blue), HSL can actually be more intuitive because it gives you direct control over the aspects of a color’s shade rather than its logical ingredients.

It is used in a similar way to rgb:


#smut { color: <strong>hsl(36, 100%, 50%)</strong> }

Rather than each sub-value being a part of the color spectrum, however, they are:

So the example used here will produce an orange (36°) that is rich (100% saturation) and vibrant (50% lightness). It is the equivalent of #ff9900, #f90, and rgb(255, 153, 0).

HSLa

Hey, man, this funky fresh transparency and HSL can be combined?! You’d better believe it. Here’s HSLa:


#rabbit { background: <strong>hsla(0, 75%, 75%, 0.5)</strong> }

hsl and hsla are supported by most modern browsers, including IE versions 9 and above.

At-Rules: @import, @media, and @font-face

At-rules encapsulate a bunch of CSS rules and apply them to something specific. They can be used to import other CSS files, apply CSS to a particular media, or embeduncommon fonts.

Each at-rule starts with an apetail, or an “at sign”, if you want to be boring about it (“@”).

Importing

Let’s start with the simple @import rule. This is used to bolt another stylesheet onto your existing one.


@import url(morestyles.css);

This can be used if a site requires long, complex stylesheets that might be easier to manage if they are broken down into smaller files.

@import rules must be placed at the top of a stylesheet, before any other rules.

Targeting media types

@media can be used to apply styles to a specific media, such as print.


<strong>@media print</strong> {
    body {
        font-size: 10pt;
        font-family: times, serif;
    }

    #navigation {
        display: none;
    }
}

Values that follow “@media” can include screen, print, projection, handheld, and all, or a comma-separated list of more than one, such as:


<strong>@media screen, projection</strong> {
    /* ... */
}

It doesn’t stop there, oh no. CSS 3 allows you to target not only specific media but also variables relating to that media, such as screen size (particularly helpful in targeting phones).

Embedding fonts

@font-face has been around for a long time but was nigh-on useless for much of its life. CSS 3 has polished it up and it is now widely used as a technique for embedding fonts in a web page so that a typeface can be used even if it isn’t sitting on the user’s computer. So you no longer need to rely on “web safe” fonts such as Arial or Verdana. Exciting times.


@font-face {
    font-family: "font of all knowledge";
    src: url(fontofallknowledge.woff);
}

What this does is create a font named “font of all knowledge” using the <strong>font-family</strong> descriptor and links the font file “fontofallknowledge.woff” to that name using the src descriptor. “font of all knowledge” can then be used in a standard font rule, such as:


p { font-family: "font of all knowledge", arial, sans-serif; }

The font will be downloaded (in this case from the same directory as the CSS file) and applied to paragraphs. If the browser is too decrepit to deal with sparkly new font-faces, it will simply revert to the next, standard, font in the list.

You can also look for a number of fonts to apply to the rule with a comma-separated list. Checking to see if a font is already present on a user’s computer, removing the need to download it, can also be accomplished by replacing “url” in the src value with “local”.

And because a font file might contain a whole host of weights or styles, you might also want to specify which one you’re interested in. So the @font-face rule could end up looking something like this:


@font-face {
    font-family: "font of all knowledge";
    src: local("font of all knowledge"), local(fontofallknowledge), url(fontofallknowledge.woff);
    font-weight: 400;
    font-style: normal;
}

Legally speaking, you can’t just throw any old font you feel like up on the Interweb because there are copyright and usage terms to consider, not to mention compatibility and optimization issues.

There are free web fonts out there that you can find, download, upload, and use, though. Hell, you could even create one yourself if you’re mad-scientist clever. There are also web font providers, such as Adobe’s Typekit, that have a large selection of fonts to choose from at a price.

Google Web Fonts has a more limited selection but it’s free to use and makes things super, super (super, super, super) easy. All you need to do is link to one of their external CSS files, which is nothing more than a @font-face rule, and whammo — you’ve got a darling new font to play with.

Attribute Selectors

What? More selectors? Because someone somewhere really wants you to keep your HTML as tidy as possible. So before you add a class attribute to a tag see if you can target it by an attribute that might already be there.

Attribute selectors allow you to style an element’s box based on the presence of an HTML attribute or of an attribute’s value.

With the attribute…

Appending an attribute name enclosed in square brackets, to style something that contains a certain attribute, you can do something like this:


<strong>abbr[title]</strong> { border-bottom: 1px dotted #ccc }

This basically says “shove a dotted line underneath all abbreviations with a title attribute”.

With the attribute and its value…

You can further specify that you want to style something with a specific attribute value.


<strong>input[type=text]</strong> { width: 200px; }

This example will apply a width of 200 pixels only to input elements that are specified as being text boxes (<input type="text">).

This approach can certainly be useful in forms where <strong>input</strong> elements can take on many guises using the type attribute.

You can also target more than one attribute at a time in a way similar to the following:


<strong>input[type=text][disabled]</strong> { border: 1px solid #ccc }

This will only apply a gray border to text inputs that are disabled.

CSS 3 further allows you to match an attribute without being exact:

So, as an example, you could style external links (eg. “http://www.htmldog.com”) differently to internal links (eg. “overhere.html”) in the following way:


a[href^=http] {
    padding-right: 10px;
    background: url(arrow.png) right no-repeat;
}

CSS Transitions

Transitions allow you to easily animate parts of your design without the need for the likes of JavaScript. How dangerous.

At the most simplistic level, think of a traditional :hover state, where you might change the appearance of a link when a cursor fondles it:


a:link {
    color: hsl(36,50%,50%);
}
a:hover {
    color: hsl(36,100%,50%);
}

This creates a binary animation; a link switches from a subdued orange to a rich orange when it is hovered over.

The transition property, however, is much more powerful, allowing smooth animation (rather than a jump from one state to another). It is a shorthand property that combines the following properties (which can be used individually if you so choose):

Returning to the shorthand property, if a transition is applied like so…


a:link {
    <strong>transition: all .5s linear 0;</strong>
    color: hsl(36,50%,50%);
}
a:hover {
    color: hsl(36,100%,50%);
}

…when the link is hovered over, the color will gradually change rather than suddenly switch. The <strong>transition</strong> property here is saying it wants all properties transitioned over half a second in a linear fashion with no delay.

For a transition to take place, only <strong>transition-duration</strong> is required, the rest defaulting to transition-property: all; transition-timing-function: ease; transition-delay: 0;. So you could, for example, simply declare transition: .5s.

Targeting specific properties

While “all” can be used in transition-property (or transition), you can tell a browser only to transition certain properties, by simply plonking in the property name you want to change. So the previous example could actually include transition: color .5s ease 0, given only the color changes.

If you want to target more than one property (without using “all”), you can offer up a comma-separated list with transition-proper<strong>ty</strong>:


a:link {
    transition: .5s;
    <strong>transition-property: color, font-size;</strong>
...

Or you can offer up a slew of rules for transitioning each property like so:


a:link {
    <strong>transition: color .5s, font-size 2s;</strong>
...

Easing

OK, so <strong>transition-timing-function</strong>. is the least obvious fella. It effectively states how the browser should deal with the intermediate states of the transition.

It follows a cubic Bézier curve. Yeah. Obviously, we know all about them from infant school, but, to get down to it, at the most basic level you can use ease or linear.

ease produces a gradual acceleration at the start of the transition and a gradual deceleration at the end. linear maintains a constant speed throughout. Other values include ease-in and ease-out.

CSS transitions won’t work in Internet Explorer versions 9 and below. Booo. But that won’t matter in cases (which will be most cases) where transitions aren’t essential for a design to work well. It’s just a little something to keep in mind.

CSS Backgrounds: Multiples, Size, and Origin

As well as plastering a single or tiling background image across parts of your page, you can also apply multiple backgrounds, adjust the size of background images, and define the origin of a background based on levels of the box model.

Multiple backgrounds

![](https://image-control-storage.s3.amazonaws.com/2023/03/11181953/multipleBackgrounds-1-1.png)
A repeating background image, a single-instance background image, and combining them together in the same box.

CSS3 allows you to apply multiple background images to a single box by simply putting image locations in a comma-separated list:


background-image: url(this.jpg), url(that.gif), url(theother.png);

More usefully, you can also define all of the other delightful background aspects. If you wanted to style a chunky button-like link with separate background, bullet, and arrow, for example, you could use something like:


background: url(bg.png), url(bullet.png) 0 50% no-repeat, url(arrow.png) right no-repeat;

Easy, right? It’s just the same as using background-image, background-position, background-repeat, background-attachment, and <strong>background</strong>, except you can specify more than one background with the aid of that helpful little comma.

Background size

The <strong>background-size</strong> property allows you to stretch or compress a background image.

![](https://image-control-storage.s3.amazonaws.com/2023/03/11181956/background-size-1.jpg)
`background-size: contain` and `background-size: cover`

The values can be:

Background Origin

background-origin is the remarkably dull kid of the bunch. Not unintelligent, just dull. The kid that the other kids point and laugh at. The property defines where the background area of a box actually starts. If you think of the box model, when you set a background it should, by default, start from the upper-left corner of the padding box. So if you had…


#burrito {
    width: 400px;
    height: 200px;
    border: 10px solid rgba(0,255,0,.5);
    padding: 20px;
    background: url(chilli.png) 0 0 no-repeat;
}

…the background image should appear in the top left corner, in the padding box, immediately after the inner edges of a green border. You can change this behavior, however, with background-origin. Its self-descriptive values can be <strong>padding-box</strong> (default, as described above), border-box, and content-box.

So adding <strong>background-origin: border-box</strong> to the previous example will cause the origin of the background image to be tucked up inside the border.

Transformations

By default, CSS boxes, those visual representations of HTML elements, are so square. Rectangular, at least; level, with four straight sides and four boring right angles. But with the use of <strong>transform</strong> you can stretch and mold those boxes into all manner of shapes.

This page will only mention the <strong>transform</strong> and transform-origin properties but, in practice, you will probably want to duplicate these with <strong>-webkit-transform</strong> and -webkit-transform-origin to achieve the same results in the likes of Safari and Chrome as well as -ms-transform and -ms-transform-origin for Internet Explorer 9, which is the earliest version of IE that will support transforms.

Manipulating a box over two dimensions, transform can be used to rotate, skew, scale and translate a box and its contents.

![](https://image-control-storage.s3.amazonaws.com/2023/03/11181957/transform-1.png)
The four basic 2D transform functions — rotate, skew, scale, and translate.

Rotating

The following would result in a square orange box with all of its contents — text, images, whatever — obediently standing to attention:


.note {
    width: 300px;
    height: 300px;
    background: hsl(36,100%,50%);
}

But you can spin those soldiers around by adding a further declaration:


transform: rotate(-10deg);

This will turn the box and, importantly, everything in it, ten degrees anti-clockwise.

Skewing

Skewing allows you to tip the horizontal and vertical so the following…


transform: skew(20deg,10deg);

…will tip over the x-axis by 20 degrees on the y-axis by 10 degrees.

You can also specify one angle, such as <strong>skew(20deg)</strong>, which is the equivalent of <strong>skew(20deg,0)</strong>.

Scaling

Obviously, you can change <strong>width</strong> and <strong>height</strong> properties on a box, but that won’t affect the size of anything inside it. Scaling, however, will multiply not only the width and height, but the size of everything contained in the box as well:


transform: scale(2);

This will multiply the size by two. You can use any positive number, including a value less than “1”, such as “0.5”, if you want to use a shrink ray.

You can also scale the horizontal and vertical dimensions separately:


transform: scale(1,2);

This will leave the horizontal as is (because it’s a scale of 1) and multiply the vertical by two.

Translating

You can shift a box horizontally and vertically using transform: translate:


transform: translate(100px,200px);

Similar to position: relative; left: 100px; top: 200px;, this will move a box 100 pixels to the right and 200 pixels down.

As well as the values mentioned, if you want to target an individual axis, you can also use skewX, skewY, scaleX, scaleY, translateX, and translateY.

Combining transformations

Want to rotate and scale at the same time? You crazy kid. You can do this by simply separating values with spaces, such as:


transform: rotate(-10deg) scale(2);

The order of the values is important – the latter will be executed before the former. In the previous example, the box will be scaled and then rotated. It is, therefore, different to transform: scale(2) rotate(-10deg);, which will be rotated and then scaled.

Alternatively, you could use the matrix function. matrix does the whole lot – rotating, skewing, scaling, and translating. It takes six values:


transform: matrix(2,-0.35,0.35,2,0,0);

These values aren’t entirely straightforward and involve maths (or just one math if you’re of the American persuasion) that, if you really want to tackle (there are benefits not only in brevity but also in precision), it may be worth giving the specs a gander.

Origin

There’s one important aspect missing. If you are transforming a box, a further parameter is involved: the transformation’s origin. If you are rotating, for example, it will, by default, turn on the point that is the center of the box; if you had a piece of card, stuck a pin right through the middle of it, and then stuck that to your forehead (don’t do this), the card would spin from the middle. You can change where in the card the pin is stuck with <strong>transform-origin</strong>, however:


transform-origin: 0 0;

This example will tell the box to transform (rotate, in the previous example) from the top left, the first “0” being horizontal, the second being vertical. These values could be different, of course — like all other x-y, and you can use the usual center, top, right, bottom, left, length and percentage values, including negatives.

![](https://image-control-storage.s3.amazonaws.com/2023/03/11181958/transform-origin-1.png)
The same clockwise-rotated box with different transform origins.

And all of that’s just with two dimensions. <strong>transform</strong> is a leviathan with even greater power that can also be used for three-dimensional magic. On the most basic level, you can use rotateX and rotateY, which will rotate “towards” or “away” from you on the x- and y-axis, and there are the likes of translate3d, scale3d, and the intimidating matrix3d, all of which have even greater browser difficulties than their 2D counterparts.

Gradients

Images showing a smooth dissolve from one color to another are plastered all over the web. However, CSS 3 allows you to place them in your designs without creating an actual image file.

There is no special property for this; you use the <strong>background</strong> or <strong>background-</strong>image property and define your gradient in its value. You can create both linear and radial gradients this way.

Linear gradients

For an even spread of two colors, fading from one at the top to another at the bottom, a declaration can be something like:


background: linear-gradient(yellow, red);

![Gradients](https://image-control-storage.s3.amazonaws.com/2023/03/11181959/linearGradient-1.png)
A simple yellow-to-red linear gradient background.

To manipulate the angle of the fading, you slot in “to” and the destination you want the transition to head to. You can head to one side:


background: linear-gradient(to right, orange, red);

Or one corner:


background: linear-gradient(to bottom right, orange, red);

Or any angle that tickles your fancy:


background: linear-gradient(20deg, orange, red);

And why stop at two colors? Specify as many as you dare:


background: linear-gradient(hsl(0,100%,50%),hsl(60,100%,50%),hsl(120,100%,50%),hsl(180,100%,50%),hsl(240,100%,50%),hsl(300,100%,50%));

![Gradients](https://image-control-storage.s3.amazonaws.com/2023/03/11182001/linearGradient2-1.png)
A colorful gradient extravaganza.

To get gradients to work on as many browsers as possible, you will probably also want to use -webkit-linear-gradient to cover Safari and older versions of Chrome. The values of these must also exclude the “to” part, if used.

CSS gradients won’t play at all with IE 9 and below, but you can still make them, and any other incapable browser, use the traditional method of a good old fashioned image by specifying that first, as a fallback (proceeding declarations will just be ignored).

So, all-in, your gradients might look something like this:


body {
    background: #666 url(fade.png) 0 0 repeat-y;
    background: -webkit-linear-gradient(right, #000, #666); 
    background: linear-gradient(to right, #000, #666);
}

See the Pen Linear Gradient by Nicholas D’Angelo (@ndangelo) on CodePen.

Radial gradients

Radial gradients, with one color starting from a central point and fading to another color, use a similar syntax:


background: radial-gradient(yellow, green);

![Gradients](https://image-control-storage.s3.amazonaws.com/2023/03/11182002/radialGradient-1.png)
A simple yellow-to-green radial gradient background.

You can also specify the shape of the fade. By default it is an ellipse, spreading to fill the background box, but you can force it to be circular, regardless of the shape of the box:


background: radial-gradient(circle, yellow, green);

![Gradients](https://image-control-storage.s3.amazonaws.com/2023/03/11182004/radialGradient2-1.png)
A circular radial gradient.

Using “closest-side”, “closest-corner”, “farthest-side” and “farthest-corner” you can also specify if the gradient is contained by the sides or corners of the box nearest to or furthest away from the origin:


background: radial-gradient(circle closest-side, yellow, green);

And if you wanted to place the origin of the gradient somewhere specific, you can also use “at”:


background: radial-gradient(at top left, yellow, green);

See the Pen Radial Gradient by Nicholas D’Angelo (@ndangelo) on CodePen.

![Gradients](https://image-control-storage.s3.amazonaws.com/2023/03/11182006/radialGradient3-1.png)
A radial gradient emanates from the top-left corner of a box.

More compatibility notes: additional -webkit-radial-gradient usage is wise. The order of the parameters needs to be changed here, and, like “to”, “at” is excluded. So:


background: radial-gradient(circle closest-side at 100px 200px , black, white);

Would be accompanied by:


background: -webkit-radial-gradient(100px 200px, circle closest-side, black, white);

Color stops

If you don’t want a uniform blend across your gradient, you can specify exactly where in the gradient each color kicks in, straight after each color, starting at “0” and ending at “100%” (although lengths can also be used).

That’s because, when the positions are stated in these examples, they evenly space out the colors, which is the default when no color stops are explicitly defined.

So, to get on with that tinkering, you can pull and stretch away with those stops:


background: linear-gradient(135deg, hsl(36,100%,50%) 10%, hsl(72,100%,50%) 60%, white 90%);

![Gradients](https://image-control-storage.s3.amazonaws.com/2023/03/11182008/linearGradient3-1.png)
Color stops in a linear gradient.

Repeating gradients

A single gradient will fill a box with the previous methods but you can use “repeating-linear-gradient” and “repeating-linear-gradient” to build on the color stops and, repeat the gradient.

For basic bars of black-and-white bars, for example:


background: repeating-linear-gradient(white, black 15px, white 30px);

![Gradients](https://image-control-storage.s3.amazonaws.com/2023/03/11182009/repeatingGradient-1.png)
A repeating linear gradient.

Or something a bit more solid:


background: repeating-radial-gradient(black, black 15px, white 15px, white 30px);

![Gradients](https://image-control-storage.s3.amazonaws.com/2023/03/11182011/repeatingGradient2-1.png)
A repeating radial gradient.

Assignment

Media Queries

@media at-rules, used to target styles at specific media, such as screen or print, have already been covered. But this can be pushed to an even greater level of sophistication, enabling you to specify different design choices depending on screen size. A page can then be optimized and laid out completely differently for mobile phones, tablets, and varying browser window sizes.

To recap, if we want to apply some CSS solely to screen-based media, for example, one option would be to slot something like the following in at the bottom of a stylesheet:


@media screen {

    body { font: 12px arial, sans-serif }
    #nav { display: block }

}

Browser-size specific CSS

To extend the previous example, not only can screen-based media be targeted, screen-based media of a certain size can be targeted as well:


<strong>@media screen and (max-width: 1000px)</strong> {

    #content { width: 100% }

}

This tells a browser to apply a block of CSS when its viewport is 1000 pixels wide or less. You could use this to do something as simple as making a content area or navigation narrower or completely re-arrange a page layout (like stacking page sections on top of one another instead of displaying them in columns).

You can apply more than one @media rule, so you could have a number of different designs that are browser-size-dependent:


@media screen and (max-width: 1000px) {

    #content { width: 100% }

}

@media screen and (max-width: 800px) {

    #nav { float: none }

}

@media screen and (max-width: 600px) {

    #content aside {
        float: none;
        display: block;
    }

}

Note that if, for example, a layout area was 600 pixels wide or less, all three of these would be applied (because it would be less than or equal to 1000px, 800px, and 600px).

As well as using a general max-width on the main content area (the article elements), this site also has a number of size-dependent CSS rules.

You could also use “min-width” instead of “max-width” if you want to do things the other way around and apply CSS to sizes equal to or over a certain length.

Orientation-specific CSS

If you have a hankering for applying CSS depending on the orientation of the browser, fill your boots with something like the following:


<strong>@media screen and (orientation: landscape)</strong> {

    #nav { float: left }

}

<strong>@media screen and (orientation: portrait)</strong> {

    #nav { float: none }

}

This could be especially useful with mobile devices…

Device-specific CSS

We’re not talking different CSS for each and every brand and model of laptop, phone, and donkey – that would be sinful – but we can, with a relatively clear conscience (as long as we’re sensible), specify the likes of the device’s screen dimensions and its pixel ratio.

A “handheld” media type does exist and it could be used as @media handheld… but it isn’t widely supported and the distinction of what is “handheld” has become blurred due to the proliferation of all manner of devices with all manner of screen sizes.

Width and height

device-width, device-height, min-device-width, max-device-width, min-device-height and max-device-height can be used to target the computed resolution of a device:


@media screen and (min-device-height: 768px) and (max-device-width: 1024px) {

    /* You can apply numerous conditions separated by "and" */

}

Pixel ratio

It’s important to keep in mind that a CSS pixel need not be the same as a physical pixel. While a screen may physically be 720 pixels wide, a browser may actually apply CSS assuming that it is 480 pixels wide, for example. This is so that a standard designed web page will more likely fit on the screen. In this example, there is a pixel ratio of 1.5:1: There are 1½ physical pixels to every CSS pixel. A standard desktop monitor will have a pixel ratio of 1:1: One CSS pixel to every physical pixel.

If you want to apply styles only to these devices, you can use something like:


@media (device-pixel-ratio: 2) {

    body { background: url(twiceasbig.png) }

}

This would apply to the likes of the iPhone (4 and above), with a pixel ratio of 2:1. You can also use min-device-pixel-ratio and max-device-pixel-ratio.

Talking of iPhones, you know the deal: also use -webkit-device-pixel-ratio, etc, etc…

You might also want to fiddle with a device’s viewport to get it to play how you want. Leaping back over to HTML, the following meta element will force a device to render a page at the width of the viewport (rather than attempting to show a wider-width design and zooming out, which it will do by default if the page can be wider than the viewport’s width) and also prevent the user from zooming in and out:


<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

The benefit of this is that you can control exactly what is applied to what physical screen size. And although it’s painful to remove user controls, if the design is delightfully swell and made just for that diddy little screen, there shouldn’t be a need to zoom.

Others

You can also apply styles depending on a device’s resolution:


@media screen and (resolution: 326dpi) { /* */ }

@media screen and (min-resolution: 96dpi) { /* */ }

Or on its aspect ratio:


@media screen and (device-aspect-ratio: 16/9) { /* */ }

From: https://www.htmldog.com/

[/read]

</body></html>




Code


Art


Design


UI/UX


Video


Projects


Social