HTML/CSS

HTML: What is HTML? | Element, Tags, and Attributes| Empty and container elements | Nesting, Parents, Children and Inheritance | HTML5 Sectional Elements | Formatting Text in HTML | Basic HTML Structure

CSS: What is CSS? | Types of CSS | How to Write CSS? | CSS selectors | CSS box model | Width & Max-Width | Block-level and Inline elements | CSS type properties | Using an Online Font Service (Google Fonts) | Viewport & Media Queries

Introduction

Front-end web development is comprised of two main coding languages: HTML and CSS (with some added Javascript in many instances). They are markup (not “programming”) languages, that are used to display and organize information on the web.


HTML

What is HTML?

HTML (Hypertext Markup Language) is a set of instructions to a browser about what information to include in a web page (text, hyperlinks, but also images, sound, and other media). It provides structure and organization for the layout of the page.

go back to top

Element, Tags, and Attributes

HTML tags mark the content of the page. For example <p> marks content as a paragraph and <header> marks the head portion of a page or an element.

Most tags come in pairs. The first opens an HTML element and the second closes it. The line below is an example of an HTML element which includes the start and end tags, as well as the content.:

    <p>This is a great day</p>

This is another html element that in which a paragraph is nested inside a div element:

    <div><p>This is a great day</p></div>

An attribute is a property of an element. It is written inside the start tag in the following form:

    <tag attribute="value">

For example the src attribute points to a file’s name and location, in the form of a URL:

    <img src="images/flower.gif" />

go back to top

Empty and container elements

Tags that enclosed content are called Container Elements. They consist of opening and closing tags and all content is placed between them. For example:

  <p>content</p>
  <h1>content</h1>

Tags that do not enclosed content are called Empty Elements. They do not have a closing tag. Instead, in XHTML they are closed with a /, for example. Here is a list of Empty Elements:

  <br>
  <link>
  <img>
  <hr>
  <meta>
  <embed>
  <param>
  <area>
  <col>
  <input>

go back to top

Nesting, Parents, Children and Inheritance

When an HTML element is ‘nested’ inside another element, such as in the code below, it is considered a child of the nesting element.

<div>
 <p>lorem ipsum</p>
</div>

Note that the closing tag of the child element appears before the closing tag of parent, so it is fully contained within the parent element.

You may have several layers of nesting, such as:

<body>
 <header>
  <div>
   <h1>
    <a href="#">lorem ipsum</a>
   </h1>
  </div>
 </header>
</body>

Child elements inherit some CSS styles from their parents. For example, the font property is inheritable, as well as the text-align and the width properties. Some properties are not inheritable such as the background-color property.

go back to top

HTML5 Sectional Elements

The following definitions are all from HTML – Living Standard:

  • The body element: The body element represents the main content of the document.
  • The header element: The header element represents a group of introductory or navigational aids.
  • The h1, h2, h3, h4, h5, and h6 elements: These elements represent headings for their sections. These elements have a rank given by the number in their name. The h1 element is said to have the highest rank, the h6 element has the lowest rank, and two elements with the same name have equal rank.
  • The nav element: The nav element represents a section of a page that links to other pages or to parts within the page: a section with navigation links.
  • The section element: The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.
  • The article element: The article element represents a self-contained composition in a document, page, application, or site and that is, in principle, independently distributable or reusable, e.g. in syndication. This could be a forum post, a magazine or newspaper article, a blog entry, a user-submitted comment, an interactive widget or gadget, or any other independent item of content.
  • The aside element: The aside element represents a section of a page that consists of content that is tangentially related to the content around the aside element, and which could be considered separate from that content. Such sections are often represented as sidebars in printed typography.It can be used for typographical effects like pull quotes or sidebars, for advertising, for groups of nav elements, and for other content that is considered separate from the main content of the page.
  • The footer element: The footer element represents a footer for its nearest ancestor sectioning content or sectioning root element. A footer typically contains information about its section such as who wrote it, links to related documents, copyright data, and the like.
  • The address element: The address element represents the contact information for its nearest article or body element ancestor. If that is the body element, then the contact information applies to the document as a whole.

go back to top

Formatting Text in HTML

The following are the most commonly used HTML elements to format text.

p – paragraph text

    <p>So she was considering in her own mind (as well as she could, for the
    day made her feel very sleepy and stupid), whether the pleasure of
    making a daisy-chain would be worth the trouble of getting up and
    picking the daisies, when suddenly a White Rabbit with pink eyes ran
    close by her. </p>

h1….h6 – titles

    <h1>Alice's Adventures in Wonderland</h1>
    <h2>Down the Rabbit-Hole</h2>

ul, li – unordered list (bullet list)

    <ul>
            <li>Alice</li>
            <li>White rabbit</li>
            <li>Caterpillar</li>
            <li>Queen</li>
     <ul>

ol, li – ordered list (number list)

     <ol>
            <li>Down the Rabbit-Hole</li>
            <li>The Pool Of Tears</li>
            <li>A Caucus-Race And A Long Tale</li>
            <li>The Rabbit Sends In A Little Bill</li>
     <ol>

Elements to Mark Emphasis or Set Text Apart

The strong element is used to indicate text that is more important than the rest of the text. More.

The em element is used for stress emphasis. It does not indicate importance but alters the meaning of the sentence. More.

The b element is used to offset part of the text for stylistic purposes, such as when we want to give it a different visual treatment. It does not convey importance or meaning. More.

The i element: used to indicate a different, voice, language or moood from the rest of the text. More.

Quoting with the blockquote and q elements

The blockquote element

Use blockquote tags to quote a sentence or a passage. You can nest any other HTML tag inside it. For example:

    <blockquote>
      <p>The reports of my death have been greatly exaggerated.</p>
      <footer>-- Mark Twain</footer>
    </blockquote>

Note that the source of the quote, which is not part of the quote but tells us something about it, is appropriately inside a footer.

The q element

Use the q tags to insert a quote into a sentence or a paragraph, such as in:

    <p><q> Curiouser and curiouser!</q> cried Alice</p>

The cite attribute

The cite attribute can be used for both blockquote and q elements to indicate a source. The cite value must be a url. For example:

    <blockquote cite="http://www.yourquotesource/source.html">

go back to top

Basic HTML structure

Every HTML page should follow this basic structure:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
  		<title>Web Page Title</title>
		<link rel="stylesheet" href="css/style.css">
  	</head>
	<body>
	</body>
</html>

Nothing would be displayed on this page as the <body> element is empty, but it has all the required tags to get started:

  • The <!DOCTYPE html> declaration lets the browser know which type of document to expect (in this case an html file).
  • The <html lang> attribute specifies the language of the element’s content (in this case English)
  • The <head> element is a container for metadata (data about data). It’s content is not displayed in the browser window.
  • <meta charset> is used to specify the character encoding for the HTML document
  • <meta name = "viewport"> is used to create responsive web pages (which adjust based on screen size)
  • The <title> specifies the title of a web page. It is displayed on search engine results pages as the clickable headline for a given result. It should be an accurate and concise description of a page’s content.
  • <link rel="stylesheet"> contains the path to the CSS sheet used to style the page
  • The <body> contains all the contents of an HTML document, such as headings, paragraphs, images, hyperlinks, tables, lists, etc. There can only be one <body> element in an HTML document.

Here are a few more common tags. You could use this code as a starting point for most HTML pages:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Web Page Title</title>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
      <div id="wrapper">
        <header>
          <h1>Site title</h1>
          <h2>Site subtitle</h2>
        </header>
        <nav>
          <ul>
            <li><a href="#">link1</a></li>
            <li><a href="#">link2</a></li>
            <li><a href="#">link3</a></li>
            <li><a href="#">link4</a></li>
            <li><a href="#">link5</a></li>
          </ul>
        </nav>
        <div id="content">
			<p>This is a paragraph</p>
        </div>
        <footer>
        </footer>
    </div>
  </body>
</html>

The <body> of this page includes :

  • A <div id="wrapper"> to “wrap around” the entire page and help us style it with CSS later
  • A <header> section with a main header <h1> and subheader <h2>
  • A <nav> section which is used to hold our main menu, comprised of an unordered list <ul> of list items <li>, each one containing a link <a>
  • A <div id="content"> to separate the main content of the page and help is style it later
  • A paragraph <p>
  • A footer <footer> often used to provide extra information and navigation options

go back to top


CSS

What is CSS?

CSS (Cascading Style Sheets) defines the style and layout of HTML elements (i.e: color, size, typography etc…)

go back to top

Types of CSS

CSS can be implemented in three different, complimentary ways: Linked, Embedded and Inline.

When applied to one web page, Inline CSS will take precedence over Embedded and Linked CSS, and Embedded CSS will take precedence over Linked CSS.

Linked CSS

When using Linked CSS, CSS code is written in a separate document saved with the extension .css. This CSS document is then linked to an HTML file in one of the following methods. Both methods require typing the following code into the head section of the HTML document.

    <link rel="stylesheet" href="http://www.revitalk.com/mmp100/mystyles.css" type="text/css">

or:

    <style type="text/css">
    @import url(mystyles.css);
    </style>

Linked CSS is a preferred method to implement CSS because:

It allows maximum separation of style and structure – all style information of a web page is contained in one document and away from the HTML code. Linked CSS can be applied to several web pages that share design.

Embedded CSS

When using embedded CSS, CSS code is written inside the head section of the HTML documents using the 

    <style type="text/css">
    .code {font-family: Courier, mono;}
    td {border: 1px;}
    </style>

Embedded CSS will apply to one web page only – the page where it is written.

Embedded CSS can be used to override linked CSS

Inline CSS

Inline CSS is written inside an HTML tag. For instance:

    <p class="code"><p style="font-size: 2em; color: red;">Inline
    CSS</p>

Inline CSS is used mainly to override embedded or linked CSS rules.

go back to top

How to write CSS

Anatomy of a CSS Rule

CSS rule

Grouping selectors

To apply the same style to two or more selectors:

   h1, p {font: verdana;}

Grouping declarations

To apply two or more styles in one CSS rule:

    td {font-size: small; background: yellow;}

CSS comments

CSS comments are ignored by browsers. This is how they are written:

    /* this is a CSS comment */
    /* CSS comments can span several lines
    and this is how to write them */

Spaces and Line Breaks

Spaces and line breaks in CSS code are ignored by browsers.

Case Sensitivity

CSS is not case sensitive except for names of font families, files, classes and ids.

go back to top

CSS Selectors

A CSS selector points to the HTML element targeted and affected by the CSS rule.

Elements selectors

Element selectors target html elements. Use element selectors when you want all page elements enclosed in a particular tag to share style. Examples:

    h1 {font: Georgia;}
    li {list-style-type: disc;}

Class selectors

To apply the same CSS rule to multiple HTML elements give them the same class and then use a CSS class selector to target them all at once.

For example,

    <p class="staffname"> 

and then in CSS:

    p.staffname {color: gray;}

If you omit the tag preceding the class name the rule will apply to any page element that has the class staffname. Note that all class names in CSS must start with a period.

The following CSS rule will affect all html elements with the class navigation:

    .navigation {font-family: arial; font-size:small;}

ID selectors

To give a page element a unique style use the id attribute in the HTML code, for example:

    <h1 id=”firstline”>

Then use an id selector to target an HTML element with a specific id, such as in:

    h1#firstline {border:0;}

If you choose to omit the tag, such as in #firstline {border:0;} the rule will apply to any HTML element with the id firstline and not only to an h1 element. Specifying the tag ensures applying this rule only to a very particular element.

Ids must be unique, i.e. must be given to only one element in a web page.

Descendant Selectors

Descendant selectors identify HTML elements by one of their ancestor elements. An ancestor is a tag that nests another tag. In the example below the p is an ancestor of strong and strong is a decedent of p.

    <p>Have a <strong>great</strong>day!</p>

Descendant selectors are a great way to pinpoint an HTML elements without the need for class or id names, i.e. saving time and keeping HTML code neater. This is how to write them

    p strong {color: red;}

And this CSS rule targets the bold line in an unordered list

    ul strong {background-color: #F7E9FF; font-weight: normal;}

Pseudo-Class Selectors

These selectors are not ‘real’ class selectors as no class is specified in the HTML code but is defined by user actions (i.e. hovering, clicking, visiting a page).

    a:link {color: blue; text-decoration: none;}

    a:visited {color: gray; text-decoration: none;}

    a:hover {color: red; text-decoration: underline;}

    a:active {color: green; text-decoration: underline;}

Note that you must write these rules in this order or they will not apply properly to hyperlinks.

go back to top

CSS box model

CSS renders HTML elements as boxes with content area and optional padding, borders and margins. All these properties can be set to be different on the different sides of the box. The CSS properties for width and height only specify the width and height of the content area.

CSS box model diagram

go back to top

Width & Max-Width

The width CSS property sets an element’s width. By default, it sets the width of the content area, but if box-sizing is set to border-box, it sets the width of the border area.

The max-width CSS property sets the maximum width of an element. It prevents the used value of the width property from becoming larger than the value specified by max-width.

go back to top

CSS units

When sizing elements with CSS, you can use different units. Here is a list of common units and when to use them (from http://thenewcode.com/775/Which-CSS-Measurements-To-Use-When):

Pixels (px):

Use for:

  • Hairline borders and general elements when creating fixed-width designs
  • Values for CSS shadow displacement.

Don’t use for: 

  • Avoid using in @media breakpoints, as doing so reinforces the tendency to create for device dimensions, rather than where your design needs to adapt. Use rem or em instead.
  • Typography. (Exception: setting a base font-size in a CSS reset).

Percentage (%)

Use for: 

Don’t use for: 

em, ex

Use for:

rem

Used as

Don’t use:

  • If you wish to support IE8 and earlier. Or, use the unit but include a fallback (by providing an alternate measurement in a more common unit before the rem measurement) or a polyfill.

go back to top

Block-level and Inline elements

Block-level are HTML elements that occupy a full horizontal line on the page. They always start in a new line.

Inline elements are HTML elements that are laid out side by side. They continue the line of the element before them and the line will wrap if they reach the right edge of the window.

Block or Inline are behaviors that are applied with CSS using the display property.

However, browsers pre-define all HTML elements as either inline or block. For example, browsers define P, DIV and H1-H6 as block levels, and IMG and SPAN as inline. You can overide this definition in your own CSS file. For example,

    h2{
    display: inline;
    }

Some CSS properties behave differently when applied to block-level and inline elements. For example, you can set the width of a block-level element.

go back to top 

CSS type properties

CSS allows you to style typography. Here are some important properties (from https://css-tricks.com/)

font-family

The font-family property defines the font that is applied to the selected element. The font that is selected is not a single font face, but a “family”, and thus may be dependent on other typographic property values to select the correct face within the family.

body {font-family: Arial, Helvetica, sans-serif;
}

A value can be one of the following:

  • A font family name that matches a font that is embedded on the page or available on the user’s system.
  • A series of family names, separated by commas, which can include a generic family name
  • If multiple family names are used, the browser will select the first one it finds either embedded on the page using @font-face or installed on the user’s operating system.

Generic family name

It is recommended to have a generic family listed last as a fallback to ensure the best typographic experience:

code {
    font-family: Courier, Monaco, monospace;
}

In the above example, “Courier” and “Monaco” are real family names of actual fonts, whereas “monospace” is just a generic reference to any font installed on the user’s system that’s monospaced.

If the first two are not found installed, the browser will select the best option, but only from monospace fonts. Without the generic family, the font would default to whatever is the default font on the user’s system (likely a serif or sans-serif), which would be undesirable.

Generic family names include serif, sans-serif, cursive, fantasy, and monospace.

If a family name matches a generic family name, the family name should be quoted to indicate that it is not generic.

Multiple Words

If a family name contains multiple words, separated by spaces, it is recommended to list the family name in quotation marks (single or double):

code {
    font-family: "Times New Roman", Georgia, serif;
}

This isn’t always necessary, but it is generally safer to include the quotes for any family name that has spaces or special characters.

Font-size

The font-size property specifies the size, or height, of the font. font-sizeaffects not only the font to which it is applied, but is also used to compute the value of em, rem, and ex length units.

p { font-size: 20px; }
em unit

The em unit is a relative unit based on the computed value of the font size of the parent element. This means that child elements are always dependent on their parent to set their font-size.

.container { 
  font-size: 16px; 
} 
p { 
  font-size: 1em; 
} 
h2 { 
  font-size: 2em; 
}

In the example above, the paragraph will have a font-size of 16px because 1 x 16 = 16px whereas the heading will be 32px because 2 x 16 = 32px. There are many advantages to scaling type up depending on the font-size of the parent element, namely we can wrap elements within a container and know that all of the children will always be relative to one another.

(Change the value on this demo to see the result).

REM unit

In the case of rem units, however, the font-size is dependent on the value of the root element (or the html element).

html { 
  font-size: 16px; 
} p { 
  font-size: 1.5rem; 
}

In the above example, the rem unit is equal to 16px (because it is inherited from the html/root element) and thus the font size for all paragraph elements will compute to 24px (1.5 x 16 = 24). Unlike em units, the paragraph will ignore the styling of all its parents besides the root.

Viewport units

Viewport units, such as vw and vh, set the font-size of an element relative to the dimensions of the viewport: 

  • 1vw = 1% of viewport width
  • 1vh = 1% of viewport height

So if we take the following example:

.element { 
  font-size: 100vh; 
}

Then this will state that the font-size of the element should always be 100% of the height of the viewport at all times (50vh would be 50%, 15vh would be 15% and so on).

(Change the value on this demo to see the result).

font-weight

The font-weight property sets the weight, or thickness, of a font and is dependent either on available font faces within a font family or weights defined by the browser.

span { 
  font-weight: bold; 
}

The font-weight property accepts either a keyword value (normal, bold, bolder, lighter) or predefined numeric value (between 100 and 900). The keyword value normal maps to the numeric value 400 and the value bold maps to 700.

(Change the value on this demo to see the result).

Color

The color property in CSS sets the color of text and text decorations.

p { 
  color: #00FFFF; 
}

The color property can accept any CSS color value:

  • Named colors: for example, “aqua”.
  • Hex colors: for example, #00FFFF or #0FF.
  • RGB and RGBa colors: for example, rgb(0, 255, 255) and rgba(0, 255, 255, .5).
  • HSL and HSLa colors: for example, hsl(180, 100%, 50%) and hsla(180, 100%, 50%, .5).

(Change the value on this demo to see the result).

Font-style

The font-style property allows you to make text appear italicized (i.e. sloped, or slanted).

em { 
  font-style: italic; 
}

This property accepts one of three possible values: normalitalic, and oblique. According to the spec, “Italic forms are generally cursive in nature while oblique faces are typically sloped versions of the regular face.” However, if the font being used does not have italic or oblique faces available, in most cases there is little, if any, difference between italic and oblique.

Line-height

The line-height property defines the amount of space above and below inline elements. That is, elements that are set to display: inline or display: inline-block. This property is most often used to set the leadingfor lines of text.

The line-height property can accept the keyword values normal or none as well as a number, length, or percentage.

The recommended method for defining line height is using a number value, referred to as a “unitless” line height. Unitless line heights are recommended due to the fact that child elements will inherit the raw number value, rather than the computed value. With this, child elements can compute their line heights based on their computed font size, rather than inheriting an arbitrary value from a parent that is more likely to need overriding.

p { 
  line-height: 1.5; 
}

Letter-spacing

The letter-spacing property controls the amount of space between each letter in a given element or block of text. Values supported by letter-spacing include font-relative values (em, rem), parent-relative values (percentage), absolute values (px) and the normal property, which resets to the font’s default. 

Using font-relative values is recommended, so that the letter-spacingincreases or decreases appropriately when the font-size is changed, either by design or by user behavior.

p {
  letter-spacing: 0.0625em;
}

(Change the value on this demo to see the result).

Text-shadow

You can add a shadow to your text with the text-shadow property.

p { 
  text-shadow: 1px 1px 1px #000; 
}

The first two values specify the length of the shadow offset. The first value specifies the horizontal distance and the second specifies the vertical distance of the shadow. The third value specifies the blur radius and the last value describes the color of the shadow:

1. value = The X-coordinate
2. value = The Y-coordinate
3. value = The blur radius
4. value = The color of the shadow

(Change the value on this demo to see the result).

Text-transform

The text-transform property in CSS controls text case and capitalization. 

.lowercase {
  text-transform: lowercase;
  }

It can take the following values:

  • lowercase makes all of the letters in the selected text lowercase.
  • uppercase makes all of the letters in the selected text uppercase.
  • capitalize capitalizes the first letter of each word in the selected text. 
  • none leaves the text’s case and capitalization exactly as it was entered.
  • inherit gives the text the case and capitalization of its parent.

(Change the value on this demo to see the result).

text-align

The text-align property in CSS is used for aligning the inner content of a block element.

p {
  text-align: center;
}

It can take the following values:

  • left – The default value. Content aligns along the left side.
  • right – Content aligns along the right side.
  • center – Content centers between the left and right edges. White space on the left and right sides of each line should be equal.
  • justify – Content spaces out such that as many blocks fit onto one line as possible and the first word on that line is along the left edge and the last word is along the right edge.
  • inherit – The value will be whatever the parent element’s is.

Text-decoration

The text-decoration property adds an underline, overline, line-through, or a combination of lines to selected text.

h3 {
  text-decoration: underline;
}

It can take the following values:

  • none: no line is drawn, and any existing decoration is removed.
  • underline: draws a 1px line across the text at its baseline.
  • line-through: draws a 1px line across the text at its “middle” point.
  • overline: draws a 1px line across the text, directly above its “top” point.
  • inherit: inherits the decoration of the parent.

(Change the value on this demo to see the result).

font-variant

The font-variant property allows you to change the targeted text to small caps. This property has been extended in CSS3.

p:first-line {
    font-variant: small-caps; /* default is `normal` */
}

(Change the value on this demo to see the result).

go back to top

Using an Online Font Service

(from: https://developer.mozilla.org/en-US/docs/Learn/CSS/Styling_text/Web_fonts)

Online font services generally store and serve fonts for you, so you don’t have to worry about writing the @font-face code, and generally just need to insert a simple line or two of code into your site to make everything work. Examples include Adobe Fonts and Cloud.typography. Most of these services are subscription-based, with the notable exception of Google Fonts, a useful free service, especially for rapid testing work and writing demos.

Let’s have a quick look at Google fonts:

  1. Go to Google Fonts.
  2. Use the filters on the left-hand side to display the kinds of fonts you want to choose and choose a couple of fonts you like.
  3. To select a font family, press the ⊕ button alongside it.
  4. When you’ve chosen the font families, press the [Number] Families Selected bar at the bottom of the page.
  5. In the resulting screen, you first need to copy the line of HTML code shown and paste it into the head of your HTML file. Put it above the existing <link> element, so that the font is imported before you try to use it in your CSS.
  6. You then need to copy the CSS declarations listed into your CSS as appropriate, to apply the custom fonts to your HTML.

go back to top

Viewport & Media Queries

The viewport is the visible part of the screen. Different devices have different viewport sizes. You can see many device viewports listed here.

At the beginning of mobile web most websites were designed for the larger viewport of a computer screen and mobile browsers adapted by scaling down the websites to fit the smaller viewport of the device. In responsive design, we need to disable this practice. We do it with the following meta element:

    <meta name="viewport" content="initial-scale=1">

Media Queries

Responsive design make use of CSS media queries to change the design at several breakpoints. Common breakpoints are:

  • Mobile portrait – 320px
  • Mobile landscape – 480px
  • Tablet portrait – 768px
  • Tablet landscape – 1024px
  • Desktop – 1224px

CSS Media queries are in the form of:

    @media (max-width: 320px) {
    }

or

    @media (min-width: 768px) {
    }

For example:

    @media (min-width: 768px) {
      .toggle-menu{display:none;}
      nav {display:block}
    }

go back to top