Blog

  • HTML5 Audio

    Embedding Audio in HTML Document

    Inserting audio onto a web page was not easy before, because web browsers did not have a uniform standard for defining embedded media files like audio.

    In this chapter we’ll demonstrates some of the many ways to embed sound in your webpage, from the use of a simple link to the use of the latest HTML5 <audio> element.

    Using the HTML5 audio Element

    The newly introduced HTML5 <audio> element provides a standard way to embed audio in web pages. However, the audio element is relatively new but it works in most of the modern web browsers.

    The following example simply inserts an audio into the HTML5 document, using the browser default set of controls, with one source defined by the src attribute.

    Exampl

    <audio controls="controls" src="media/birds.mp3">
        Your browser does not support the HTML5 Audio element.
    </audio>

    An audio, using the browser default set of controls, with alternative sources.

    Example

    <audio controls="controls">
        <source src="media/birds.mp3" type="audio/mpeg">
        <source src="media/birds.ogg" type="audio/ogg">
        Your browser does not support the HTML5 Audio element.
    </audio>

    The ‘ogg’ track in the above example works in Firefox, Opera and Chrome, while the same track in the ‘mp3’ format is added to make the audio work in Internet Explorer and Safari.


    Linking Audio Files

    You can make links to your audio files and play it by ticking on them.

    Let’s try out the following example to understand how this basically works:

    Example

    <a href="media/sea.mp3">Track 1</a>
    <a href="media/wind.mp3">Track 2</a>

    Using the object Element

    The <object> element is used to embed different kinds of media files into an HTML document. Initially, this element was used to insert ActiveX controls, but according to the specification, an object can be any media object such as audio, video, PDF files, Flash animations or even images.

    The following example code embeds a simple audio file into a web page.

    Example

    <object data="media/sea.mp3"></object>
    <object data="media/sea.ogg"></object>

    Warning: The <object> element is not supported widely and very much depends on the type of the object that’s being embedded. Other methods like HTML5 <audio> element or third-party HTML5 audio players could be a better choice in many cases.


    Using the embed Element

    The <embed> element is used to embed multimedia content into an HTML document.

    The following code fragment embeds audio files into a web page.

    Example

    <embed src="media/wind.mp3">
    <embed src="media/wind.ogg">
  • HTML5 SVG

    What is SVG?

    The Scalable Vector Graphics (SVG) is an XML-based image format that is used to define two-dimensional vector based graphics for the web. Unlike raster image (e.g. .jpg.gif.png, etc.), a vector image can be scaled up or down to any extent without losing the image quality.

    An SVG image is drawn out using a series of statements that follow the XML schema — that means SVG images can be created and edited with any text editor, such as Notepad. There are several other advantages of using SVG over other image formats like JPEG, GIF, PNG, etc.

    • SVG images can be searched, indexed, scripted, and compressed.
    • SVG images can be created and modified using JavaScript in real time.
    • SVG images can be printed with high quality at any resolution.
    • SVG content can be animated using the built-in animation elements.
    • SVG images can contain hyperlinks to other documents.

    Tip: The vector images are composed of a fixed set of shapes defined by math, while the bitmap or raster images are composed of a fixed set of dots called pixels.


    Embedding SVG into HTML Pages

    You can embed SVG graphics directly into your document using the HTML5 <svg> element.

    Let’s take a look at the following example to understand how it basically works:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Embedding SVG in HTML</title>
    </head>
    <body>
        <svg width="300" height="200">
            <text x="10" y="20" style="font-size:14px;">
                Your browser support SVG.
            </text>
            Sorry, your browser does not support SVG.
        </svg>
    </body>
    </html>

    Note: All the major modern web browsers like Chrome, Firefox, Safari, and Opera, as well as Internet Explorer 9 and above support inline SVG rendering.


    Drawing Path and Shapes with SVG

    The following section will explain you how to draw basic vector-based paths and shapes on the web pages using the newly introduced HTML5 <svg> element.

    Drawing a Line

    The most basic path you can draw with SVG is a straight line. The following example will show you how to create a straight line using the SVG <line> element:

    Example

    <svg width="300" height="200">
        <line x1="50" y1="50" x2="250" y2="150" style="stroke:red; stroke-width:3;" />
    </svg>

    The attributes x1x2y1 and y2 of the <line> element draw a line from (x1,y1) to (x2,y2).


    Drawing a Rectangle

    You can create simple rectangle and square shapes using the SVG <rect> element. The following example will show you how to create and style a rectangular shape with SVG:

    Example

    <svg width="300" height="200">
        <rect x="50" y="50" width="200" height="100" style="fill:orange; stroke:black; stroke-width:3;" />
    </svg>

    The attributes x and y of <rect> element defines the co-ordinates of the top-left corner of the rectangle. The attributes width and height specifies the width and height of the shape.


    Drawing a Circle

    You can also create the circle shapes using the SVG <circle> element. The following example will show you how to create and style a circular shape with SVG:

    Example

    <svg width="300" height="200">
        <circle cx="150" cy="100" r="70" style="fill:lime; stroke:black; stroke-width:3;" />
    </svg>

    The attributes cx and cy of the <circle> element defines the co-ordinates of the center of the circle and the attribute r specifies the radius of the circle. However, if the attributes cx and cy are omitted or not specified, the center of the circle is set to (0,0).


    Drawing Text with SVG

    You can also draw text on the web pages with SVG. The text in SVG is rendered as a graphic so you can apply all the graphic transformation to it but it is still acts like text — that means it can be selected and copied as text by the user. Let’s try an example to see how this works:

    Example

    <svg width="300" height="200">
        <text x="20" y="30" style="fill:purple; font-size:22px;">
            Welcome to Our Website!
        </text>
        <text x="20" y="30" dx="0" dy="20" style="fill:navy; font-size:14px;">
            Here you will find lots of useful information.
        </text>
    </svg>

    The attributes x and y of the <text> element defines the location of the top-left corner in absolute terms whereas the attributes dx and dy specifies the relative location.

    You can even use the <tspan> element to reformat or reposition the span of text contained within a <text> element. Text contained in separate tspans, but inside the same text element can all be selected at once — when you click and drag to select the text. However, the text in separate text elements cannot be selected at the same time. Let’s check out an example:

    Example

    <svg width="300" height="200">
        <text x="30" y="15" style="fill:purple; font-size:22px; transform:rotate(30deg);">
            <tspan style="fill:purple; font-size:22px;">
                Welcome to Our Website!
            </tspan>
            <tspan dx="-230" dy="20" style="fill:navy; font-size:14px;">
                Here you will find lots of useful information.
            </tspan>
        </text>
    </svg>

    Differences between SVG and Canvas

    The HTML5 introduced the two new graphical elements <canvas> and <svg> for creating rich graphics on the web, but they are fundamentally different.

    The following table summarizes some of the basic differences between these two elements, which will help you to understand how to use these elements effectively and appropriately.

    SVGCanvas
    Vector based (composed of shapes)Raster based (composed of pixel)
    Multiple graphical elements, which become the part of the page’s DOM treeSingle element similar to <img> in behavior. Canvas diagram can be saved to PNG or JPG format
    Modified through script and CSSModified through script only
    Good text rendering capabilitiesPoor text rendering capabilities
    Give better performance with smaller number of objects or larger surface, or bothGive better performance with larger number of objects or smaller surface, or both
    Better scalability. Can be printed with high quality at any resolution. Pixelation does not occurPoor scalability. Not suitable for printing on higher resolution. Pixelation may occur
  • HTML5 Canvas

    What is Canvas?

    The HTML5 canvas element can be used to draw graphics on the webpage via JavaScript. The canvas was originally introduced by Apple for the Mac OS dashboard widgets and to power graphics in the Safari web browser. Later it was adopted by the Firefox, Google Chrome and Opera. Now the canvas is a part of the new HTML5 specification for next generation web technologies.

    By default the <canvas> element has 300px of width and 150px of height without any border and content. However, custom width and height can be defined using the CSS height and width property whereas the border can be applied using the CSS border property.

    Understanding Canvas Coordinates

    The canvas is a two-dimensional rectangular area. The coordinates of the top-left corner of the canvas are (0, 0) which is known as origin, and the coordinates of the bottom-right corner are (canvas widthcanvas height). Here’s a simple demonstration of canvas default coordinate system.


    (0,0)

    Tip: Place your mouse pointer within the canvas area demonstrated above and you will get its current coordinates relative to the canvas. The <canvas> element is supported in all major web browsers such as Chrome, Firefox, Safari, Opera, IE 9 and above.


    Drawing Path and Shapes on Canvas

    In this section we’re going to take a closer look at how to draw basic paths and shapes using the newly introduced HTML5 canvas element and JavaScript.

    Here is the base template for drawing paths and shapes onto the 2D HTML5 canvas.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Drawing on Canvas</title>
    <script>
        window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            // draw stuff here
        };
    </script>
    </head>
    <body>
        <canvas id="myCanvas" width="300" height="200"></canvas>
    </body>
    </html>

    All the lines except those from 7 to 11 are pretty straight forward. The anonymous function attached to the window.onload event will execute when the page load. Once the page is loaded, we can access the canvas element with document.getElementById() method. Later we have defined a 2D canvas context by passing 2d into the getContext() method of the canvas object.

    Drawing a Line

    The most basic path you can draw on canvas is a straight line. The most essential methods used for this purpose are moveTo()lineTo() and the stroke().

    The moveTo() method defines the position of drawing cursor onto the canvas, whereas the lineTo() method used to define the coordinates of the line’s end point, and finally the stroke() method is used to make the line visible. Let’s try out an example:

    Example

    <script>
        window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.moveTo(50, 150);
            context.lineTo(250, 50);
            context.stroke();
        };
    </script>

    Drawing a Arc

    You can create arcs using the arc() method. The syntax of this method is as follow:

    context.arc(centerX, centerY, radius, startingAngle, endingAngle, counterclockwise);

    The JavaScript code in the following example will draw an arc on the canvas.

    Example

    <script>
        window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.arc(150, 150, 80, 1.2 * Math.PI, 1.8 * Math.PI, false);
            context.stroke();
        };
    </script>

    Drawing a Rectangle

    You can create rectangle and square shapes using the rect() method. This method requires four parameters x, y position of the rectangle and its width and height.

    The basic syntax of the rect() method can be given with:

    context.rect(x, y, width, height);

    The following JavaScript code will draw a rectangle shape centered on the canvas.

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.rect(50, 50, 200, 100); 
            context.stroke();
        };
    </script>

    Drawing a Circle

    There is no specific method for creating circle like rectangle’s rect() method. However, you can create a fully enclosed arc such as circle using the arc() method.

    The syntax for drawing a complete circle using the arc() method can be given with:

    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);

    The following example will draw a complete circle centered on the canvas.

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.arc(150, 100, 70, 0, 2 * Math.PI, false);
            context.stroke();
        };
    </script>

    Applying Styles and Colors on Stroke

    The default color of the stroke is black and its thickness is one pixel. But, you can set the color and width of the stoke using the strokeStyle and lineWidth property respectivley.

    The following example will draw an orange color line having 5 pixels width.

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.lineWidth = 5;
            context.strokeStyle = "orange";
            context.moveTo(50, 150);
            context.lineTo(250, 50);
            context.stroke();
        };
    </script>

    You can also set the cap style for the lines using the lineCap property. There are three styles available for the line caps — butt, round, and square. Here’s an example:

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.lineWidth = 10;
            context.strokeStyle = "orange";
            context.lineCap = "round";
            context.arc(150, 150, 80, 1.2 * Math.PI, 1.8 * Math.PI, false);
            context.stroke();
        };
    </script>

    Filling Colors inside Canvas Shapes

    You can also fill color inside the canvas shapes using the fillStyle() method.

    The following example will show you how to fill a solid color inside a rectangle shape.

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.rect(50, 50, 200, 100); 
            context.fillStyle = "#FB8B89";
            context.fill();
            context.lineWidth = 5;
            context.strokeStyle = "black";
            context.stroke();
        };
    </script>

    Tip: While styling the shapes on canvas, it is recommended to use the fill() method before the stroke() method in order to render the stroke correctly.

    Similarly, you can use the fillStyle() method to fill solid color inside a circle too.

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.arc(150, 100, 70, 0, 2 * Math.PI, false);
            context.fillStyle = "#FB8B89";
            context.fill();
            context.lineWidth = 5;
            context.strokeStyle = "black";
            context.stroke();
        };
    </script>

    Filling Gradient Colors inside Canvas Shapes

    You can also fill gradient color inside the canvas shapes. A gradient is just a smooth visual transition from one color to another. There are two types of gradient available — linear and radial.

    The basic syntax for creating a linear gradient can be given with:

    var grd = context.createLinearGradient(startX, startY, endX, endY);

    The following example uses the createLinearGradient() method to fill a linear gradient color inside a rectangle. Let’s try it out to understand how it basically works:

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.rect(50, 50, 200, 100); 
            var grd = context.createLinearGradient(0, 0, canvas.width, canvas.height);
            grd.addColorStop(0, '#8ED6FF');   
            grd.addColorStop(1, '#004CB3');
            context.fillStyle = grd;
            context.fill();
            context.stroke();
        };
    </script>

    Similarly, you can fill canvas shapes with radial gradient using the createRadialGradient() method. The basic syntax for creating a radial gradient can be given with:

    var grd = context.createRadialGradient(startX, startY, startRadius, endX, endY, endRadius);

    The following example uses the createRadialGradient() method to fill a radial gradient color inside a circle. Let’s try it out to understand how it actually works:

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.arc(150, 100, 70, 0, 2 * Math.PI, false);
            var grd = context.createRadialGradient(150, 100, 10, 160, 110, 100);
            grd.addColorStop(0, '#8ED6FF');   
            grd.addColorStop(1, '#004CB3');
            context.fillStyle = grd;
            context.fill();
            context.stroke();
        };
    </script>

    Drawing Text on Canvas

    You can also draw text onto canvas. These texts can contain any Unicode characters. The following example will draw a simple greeting message “Hello World!” onto a canvas.

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.font = "bold 32px Arial";
            context.fillText("Hello World!", 50, 100);
        };
    </script>

    You can additionally set the color and alignment of the text on the canvas, like this:

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.font = "bold 32px Arial";
            context.textAlign = "center";
            context.textBaseline = "middle";
            context.fillStyle = "orange";
            context.fillText("Hello World!", 150, 100);
        };
    </script>

    You can also apply stroke on text using the strokeText() method. This method will color the perimeter of the text instead of filling it. However if you want to set both the fill and stroke on canvas text you can use both the fillText() and the strokeText() methods together.

    Example

    <script>
    	window.onload = function() {
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            context.font = "bold 32px Arial";
            context.textAlign = "center";
            context.textBaseline = "middle";
            context.strokeStyle = "orange";
            context.strokeText("Hello World!", 150, 100);
        };
    </script>
  • HTML5 New Input Types

    New Input Types in HTML5

    HTML5 introduces several new <input> types like email, date, time, color, range, and so on. to improve the user experience and to make the forms more interactive. However, if a browser failed to recognize these new input types, it will treat them like a normal text box.

    In this section we’re going to take a brief look at each of the following new input types:

    • color
    • date
    • datetime-local
    • email
    • month
    • number
    • range
    • search
    • tel
    • time
    • url
    • week

    There was also a datetime input type for entering a date and time, but it is now obsolete.


    Input Type Color

    The color input type allows the user to select a color from a color picker and returns the color value in hexadecimal format (#rrggbb). If you don’t specify a value, the default is #000000, which is black.

    Let’s try out the following example to understand how it basically works:

    Example

    <form>
        <label for="mycolor">Select Color:</label>
        <input type="color" value="#00ff00" id="mycolor">
    </form>

    Note: The color input (i.e. type="color") is supported in all major modern web browsers such as Firefox, Chrome, Opera, Safari (12.1+), Edge (14+). Not supported by the Microsoft Internet Explorer and older version of Apple Safari browsers.


    Input Type Date

    The date input type allows the user to select a date from a drop-down calendar.

    The date value includes the year, month, and day, but not the time.

    Example

    <form>
        <label for="mydate">Select Date:</label>
        <input type="date" value="2019-04-15" id="mydate">
    </form>

    Note: The date input (i.e. type="date") is supported by the Chrome, Firefox, Opera and Edge browsers. Not supported by the Internet Explorer and Safari browsers.


    Input Type Datetime-local

    The datetime-local input type allows the user to select both local date and time, including the year, month, and day as well as the time in hours and minutes.

    Let’s try out the following example to understand how it basically works:

    Example

    <form>
        <label for="mydatetime">Choose Date and Time:</label>
        <input type="datetime-local" id="mydatetime">
    </form>
    
    

    Input Type Email

    The email input type allows the user to enter e-mail address. It is very similar to a standard text input type, but if it is used in combination with the required attribute, the browser may look for the patterns to ensure a properly-formatted e-mail address should be entered.

    Let’s try out this example by entering any e-mail address to see how it actually works:

    Example

    <form>
        <label for="myemail">Enter Email Address:</label>
        <input type="email" id="myemail" required>
    </form>

    Tip: You can style the email input field for different validation states, when an value is entered using the :valid:invalid or :required pseudo-classes.

    Note: The validation for the email input (i.e. type="email") is supported by all major browsers like Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above.


    Input Type Month

    The month input type allows the user to select a month and year from a drop-down calendar.

    The value is a string in the format “YYYY-MM”, where YYYY is the four-digit year and MM is the month number. Let’s try out an example to see how this basically works:

    Example

    <form>
        <label for="mymonth">Select Month:</label>
        <input type="month" id="mymonth">
    </form>
    
    

    Input Type Number

    The number input type can be used for entering a numerical value. You can also restrict the user to enter only acceptable values using the additional attributes minmax, and step.

    The following example will allow you to enter a numeric value between 1 to 10.

    Example

    <form>
        <label for="mynumber">Enter a Number:</label>
        <input type="number" min="1" max="10" step="0.5" id="mynumber">
    </form>

    Note: The number input (i.e. type="number") is supported by all major web browsers such as Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above. Internet Explorer however recognized the number but do not provide increment and decrement spin buttons.


    Input Type Range

    The range input type can be used for entering a numerical value within a specified range. It works very similar to number input, but it offers a simpler control for entering a number.

    Let’s try out the following example to understand how it basically works:

    Example

    <form>
        <label for="mynumber">Select a Number:</label>
        <input type="range" min="1" max="10" step="0.5" id="mynumber">    
    </form>

    Note: The range input (i.e. type="range") is supported by all major web browsers such as Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above.


    Input Type Search

    The search input type can be used for creating search input fields.

    A search field typically behaves like a regular text field, but in some browsers like Chrome and Safari as soon as you start typing in the search box a small cross appears on the right side of the field that lets you quickly clear the search field. Let’s try out an example to see how it works:

    Example

    <form>
        <label for="mysearch">Search Website:</label>
        <input type="search" id="mysearch">
    </form>

    Note: The search input (i.e. type="search") is supported by all major web browsers such as Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above.


    Input Type Tel

    The tel input type can be used for entering a telephone number.

    Browsers don’t support tel input validation natively. However, you can use the placeholder attribute to help users in entering the correct format for a phone number, or specify a regular expression to validate the user input using the pattern attribute. Let’s check out an example:

    Example

    <form>
        <label for="myphone">Telephone Number:</label>
        <input type="tel" id="myphone" placeholder="xx-xxxx-xxxx" required>
    </form>

    Note: The validation for tel input (i.e. type="tel") is currently not supported by any browser because format for phone numbers vary so much across countries, but it is still useful. Mobile browsers display a numeric keyboard for tel input field for entering phone numbers.


    Input Type Time

    The time input type can be used for entering a time (hours and minutes).

    Browser may use 12- or 24-hour format for inputting times, based on local system’s time setting.

    Example

    Try this code »

    <form>
        <label for="mytime">Select Time:</label>
        <input type="time" id="mytime">
    </form>
    
    

    Input Type URL

    The url input type can be used for entering URL’s or web addresses.

    You can use the multiple attribute to enter more than one URL. Also, if required attribute is specified browser will automatically carry out validation to ensure that only text that matches the standard format for URLs is entered into the input box. Let’s see how this works:

    Example

    <form>
        <label for="myurl">Enter Website URL:</label>
        <input type="url" id="myurl" required>
    </form>

    Note: The validation for the url input (i.e. type="url") is supported by all major browsers like Firefox, Chrome, Safari, Opera, Internet Explorer 10 and above.


    Input Type Week

    The week input type allows the user to select a week and year from a drop-down calendar.

    Let’s try out the following example to understand how this works:

    Example

    <form>
        <label for="myweek">Select Week:</label>
        <input type="week" id="myweek">
    
  • HTML Head

    The HTML head Element

    The <head> element primarily is the container for all the head elements, which provide extra information about the document (metadata), or reference to other resources that are required for the document to display or behave correctly in a web browser.

    The head elements collectively describes the properties of the document such as title, provide meta information like character set, instruct the browser where to find the style sheets or scripts that allows you to extend the HTML document in a highly active and interactive ways.

    The HTML elements that can be used inside the <head> element are: <title><base><link><style><meta><script> and the <noscript> element.

    The HTML title Element

    The <title> element defines the title of the document.

    The title element is required in all HTML/XHTML documents to produce a valid document. Only one title element is permitted in a document and it must be placed within the <head> element. The title element contains plain text and entities; it may not contain other markup tags.

    The title of the document may be used for different purposes. For example:

    • To display a title in the browser title bar and in the task bar.
    • To provide a title for the page when it is added to favorites or bookmarked.
    • To displays a title for the page in search-engine results.

    The following example demonstrates how to place title in an HTML document.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>A simple HTML document</title>
    </head>
    <body>
        <p>Hello World!</p>
    </body>
    </html>

    Tip: A good title should be short and specific to the document’s content, because search engine’s web crawlers pay particular attention to the words used in the title. The title should ideally be less than 65 characters in length. See the guidelines for titles.


    The HTML base Element

    The HTML <base> element is used to define a base URL for all relative links contained in the document, e.g. you can set the base URL once at the top of your page, and then all subsequent relative links will use that URL as a starting point. Here’s an example:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>Defining a base URL</title>
        <base href="https://www.tutorialrepublic.com/">
    </head>
    <body>
        <p><a href="html-tutorial/html-head.php">HTML Head</a>.</p>
    </body>
    </html>

    The hyperlink in the example above will actually resolve to https://www.foobrdigital.com/html-tutorial/html-head.php regardless of the URL of the current page. This is because the relative URL specified in the link: html-tutorial/html-head.php is added to the end of the base URL: https://www.tutorialrepublic.com/.

    Warning: The HTML <base> element must appear before any element that refers to an external resource. HTML permits only one base element for each document.


    The HTML link Element

    The <link> element defines the relationship between the current document and an external documents or resources. A common use of link element is to link to external style sheets.

    Example

    <head>
        <title>Linking Style Sheets</title>
        <link rel="stylesheet" href="style.css">
    </head>

    Please check out the CSS tutorial section to learn about style sheets in detail.

    Note: An HTML document’s <head> element may contain any number of <link> elements. The <link> element has attributes, but no contents.


    The HTML style Element

    The <style> element is used to define embedded style information for an HTML document. The style rules inside the <style> element specify how HTML elements render in a browser.

    Example

    <head>
        <title>Embedding Style Sheets</title>
        <style>
            body { background-color: YellowGreen; }
            h1 { color: red; }
            p { color: green; }
        </style>
    </head>

    Note: An embedded style sheet should be used when a single document has a unique style. If the same style sheet is used in multiple documents, then an external style sheet would be more appropriate. See the tutorial on HTML styles to learn more about it.


    The HTML meta Element

    The <meta> element provides metadata about the HTML document. Metadata is a set of data that describes and gives information about other data. Here’s an example:

    Example

    <head>
        <title>Specifying Metadata</title>
        <meta charset="utf-8">
        <meta name="author" content="John Smith">
    </head>

    The meta element will be explained in more detail in the next chapter.


    The HTML script Element

    The <script> element is used to define client-side script, such as JavaScript in HTML documents.

    The following example will display a greeting message in the browser:

    Example

    <head>
        <title>Adding JavaScript</title>
        <script>
            document.write("<h1>Hello World!</h1>") 
        </script>
    </head>

    The script and noscript element will be explained in detail in the later chapter.

  • HTML Layout

    Creating Website Layouts

    Creating a website layout is the activity of positioning the various elements that make a web page in a well-structured manner and give appealing look to the website.

    You have seen most websites on the internet usually display their content in multiple rows and columns, formatted like a magazine or newspaper to provide the users a better reading and writing environment. This can be easily achieved by using the HTML tags, such as <table><div><header><footer><section>, etc. and adding some CSS styles to them.

    HTML Table Based Layout

    Table provides the simplest way for creating layouts in HTML. Generally, this involves the process of putting the contents such as text, images, and so on into rows and columns.

    The following layout is created using an HTML table with 3 rows and 2 columns — the first and last row spans both columns using the table’s colspan attribute:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>HTML Table Layout</title>
    </head>
    <body style="margin:0px;">
        <table style="width:100%; border-collapse:collapse; font:14px Arial,sans-serif;">
            <tr>
                <td colspan="2" style="padding:10px 20px; background-color:#acb3b9;">
                    <h1 style="font-size:24px;">Tutorial Republic</h1>
                </td>
            </tr>
            <tr style="height:170px;">
                <td style="width:20%; padding:20px; background-color:#d4d7dc; vertical-align: top;">
                    <ul style="list-style:none; padding:0px; line-height:24px;">
                        <li><a href="#" style="color:#333;">Home</a></li>
                        <li><a href="#" style="color:#333;">About</a></li>
                        <li><a href="#" style="color:#333;">Contact</a></li>
                    </ul>
                </td>
                <td style="padding:20px; background-color:#f2f2f2; vertical-align:top;">
                    <h2>Welcome to our site</h2>
                    <p>Here you will learn how to create websites...</p>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="padding:5px; background-color:#acb3b9; text-align:center;">
                    <p>copyright &copy; tutorialrepublic.com</p>
                </td>
            </tr>
        </table>
    </body>
    </html>

    — The HTML code above will produce the following output:https://www.tutorialrepublic.com/examples/html/table-layout.html

    Warning: The method used for creating layout in the above example is not wrong, but it’s not recommended. Avoid tables and inline styles for creating layouts. Layouts created using tables often rendered very slowly. Tables should only be used to display tabular data.


    HTML Div Based Layout

    Using the <div> elements is the most common method of creating layouts in HTML. The <div> (stands for division) element is used for marking out a block of content, or set of other elements inside an HTML document. It can contain further other div elements if required.

    The following example uses the div elements to create a multiple column layout. It will produce the same result as in the previous example that uses table element:

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>HTML Div Layout</title>
    <style>
        body {
            font: 14px Arial,sans-serif; 
            margin: 0px;
        }
        .header {
            padding: 10px 20px;
            background: #acb3b9; 
        }
        .header h1 {
            font-size: 24px;
        }
        .container {
            width: 100%;
            background: #f2f2f2; 
        }
        .nav, .section {
            float: left; 
            padding: 20px;
            min-height: 170px;
            box-sizing: border-box;
        }
        .nav {            
            width: 20%;             
            background: #d4d7dc;
        }
        .section {
            width: 80%;
        }
        .nav ul {
            list-style: none; 
            line-height: 24px;
            padding: 0px; 
        }
        .nav ul li a {
            color: #333;
        }    
        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }
        .footer {
            background: #acb3b9;            
            text-align: center;
            padding: 5px;
        }
    </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h1>Tutorial Republic</h1>
            </div>
            <div class="wrapper clearfix">
                <div class="nav">
                    <ul>
                        <li><a href="#">Home</a></li>
                        <li><a href="#">About</a></li>
                        <li><a href="#">Contact</a></li>
                    </ul>
                </div>
                <div class="section">
                    <h2>Welcome to our site</h2>
                    <p>Here you will learn how to create websites...</p>
                </div>
            </div>
            <div class="footer">
                <p>copyright &copy; tutorialrepublic.com</p>
            </div>
        </div>
    </body>
    </html>

    — The HTML code above will produce the same output as the previous example:https://www.tutorialrepublic.com/examples/html/div-layout.html

    We’ve created this layout using the CSS float techniques, since most web browsers support it. Alternatively, you can also use the CSS3 flexbox to create modern and more flexible layouts. See the tutorial on CSS3 flexible box layouts to learn about flexbox in detail.

    Tip: Better web page layouts can be created by using the DIV elements and CSS. You can change the layout of all the pages of your website by editing just one CSS file. To learn about CSS in detail, please check out our CSS tutorial section.


    Using the HTML5 Structural Elements

    HTML5 has introduced the new structural elements such as <header><footer><nav><section>, etc. to define the different parts of a web page in a more semantic way.

    You can consider these elements as a replacement for commonly used classes such as .header.footer.nav.section, etc. The following example uses the new HTML5 structural elements to create the same layout that we have created in the previous examples.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>HTML5 Web Page Layout</title>
    <style>
        body {
            font: 14px Arial,sans-serif; 
            margin: 0px;
        }
        header {
            padding: 10px 20px;
            background: #acb3b9; 
        }
        header h1 {
            font-size: 24px;
        }
        .container {
            width: 100%;
            background: #f2f2f2;  
        }
        nav, section {
            float: left; 
            padding: 20px;
            min-height: 170px;
            box-sizing: border-box;
        }
        section {
            width: 80%;
        }
        nav {
            width: 20%;             
            background: #d4d7dc;
        }    
        nav ul {
            list-style: none; 
            line-height: 24px;
            padding: 0px; 
        }
        nav ul li a {
            color: #333;
        }
        .clearfix:after {
            content: ".";
            display: block;
            height: 0;
            clear: both;
            visibility: hidden;
        }
        footer {
            background: #acb3b9;            
            text-align: center;
            padding: 5px;
        }
    </style>
    </head>
    <body>
        <div class="container">
            <header>
                <h1>Tutorial Republic</h1>
            </header>
            <div class="wrapper clearfix">
                <nav>
                    <ul>
                        <li><a href="#">Home</a></li>
                        <li><a href="#">About</a></li>
                        <li><a href="#">Contact</a></li>
                    </ul>
                </nav>
                <section>
                    <h2>Welcome to our site</h2>
                    <p>Here you will learn how to create websites...</p>
                </section>
            </div>
            <footer>
                <p>copyright &copy; tutorialrepublic.com</p>
            </footer>
        </div>
    </body>
    </html>

    — The HTML code above will also produce the same output as the previous example:https://www.tutorialrepublic.com/examples/html5/semantic-website-layout.html

    The following table provides a brief overview of new HTML5 structural elements.

    TagDescription
    <header>Represents the header of a document or a section.
    <footer>Represents the footer of a document or a section.
    <nav>Represents a section of navigation links.
    <section>Represents a section of a document, such as header, footer etc.
    <article>Represents an article, blog post, or other self-contained unit of information.
    <aside>Represents some content loosely related to the page content.

    Please check out the reference on HTML5 tags to know about the newly introduced tags.

  • HTML Doctypes

    Understanding the HTML5 Doctype

    A Document Type Declaration, or DOCTYPE for short, is an instruction to the web browser about the version of markup language in which a web page is written.

    A DOCTYPE declaration appears at the top of a web page before all other elements. According to the HTML specification or standards, every HTML document requires a valid document type declaration to insure that your web pages are displayed the way they are intended to be displayed.

    The doctype declaration is usually the very first thing defined in an HTML document (even before the opening <html> tag); however the doctype declaration itself is not an HTML tag.

    The DOCTYPE for HTML5 is very short, concise, and case-insensitive.

    <!DOCTYPE html>

    Doctypes for earlier versions of HTML were longer because the HTML language was SGML-based and therefore required a reference to a DTD, but they are obsolete now.

    With HTML5 this is no longer the case and the doctype declaration is only needed to enable the standard mode for documents written using the HTML syntax.

    You can use the following markup as a template to create a new HTML5 document.

    Example

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <title><!-- Insert your title here --></title>
    </head>
    <body>
        <!-- Insert your content here -->
    </body>
    </html>
  • HTML iFrame

    What is iframe

    An iframe or inline frame is used to display external objects including other web pages within a web page. An iframe pretty much acts like a mini web browser within a web browser. Also, the content inside an iframe exists entirely independent from the surrounding elements.

    The basic syntax for adding an iframe to a web page can be given with:

    <iframe src=”URL“></iframe>

    The URL specified in the src attribute points to the location of an external object or a web page.

    The following example display “hello.html” file inside an iframe in current document.

    Example

    <iframe src="hello.html"></iframe>

    Setting Width and Height of an iFrame

    The height and width attributes are used to specify the height and width of the iframe.

    Example

    <iframe src="hello.html" width="400" height="200"></iframe>

    You can also use CSS to set the width and height of an iframe, as shown here:

    Example

    <iframe src="hello.html" style="width: 400px; height: 200px;"></iframe>

    Please see the tutorial on HTML styles to learn the methods of applying CSS to HTML elements.

    Note: The width and height attribute values are specified in pixels by default, but you can also set these values in percentage, such as 50%, 100% and so on. The default width of an iframe is 300 pixels, whereas the default height is 150 pixels.


    Removing Default Frameborder

    The iframe has a border around it by default. However, if you want to modify or remove the iframe borders, the best way is to use the CSS border property.

    The following example will simply render the iframe without any borders.

    Example

    <iframe src="hello.html" style="border: none;"></iframe>

    Similarly, you can use the border property to add the borders of your choice to an iframe. The following example will render the iframe with 2 pixels blue border.

    Example

    <iframe src="hello.html" style="border: 2px solid blue;"></iframe>

    Using an iFrame as Link Target

    An iframe can also be used as a target for the hyperlinks.

    An iframe can be named using the name attribute. This implies that when a link with a target attribute with that name as value is clicked, the linked resource will open in that iframe.

    Let’s try out an example to understand how it basically works:

    Example

    <iframe src="demo-page.html" name="myFrame"></iframe>
    <p><a href="https://www.tutorialrepublic.com" target="myFrame">Open TutorialRepublic.com</a></p>
  • HTML Forms

    What is HTML Form

    HTML Forms are required to collect different kinds of user inputs, such as contact details like name, email address, phone numbers, or details like credit card information, etc.

    Forms contain special elements called controls like inputbox, checkboxes, radio-buttons, submit buttons, etc. Users generally complete a form by modifying its controls e.g. entering text, selecting items, etc. and submitting this form to a web server for further processing.

    The <form> tag is used to create an HTML form. Here’s a simple example of a login form:

    Example

    <form>
        <label>Username: <input type="text"></label>
        <label>Password: <input type="password"></label>
        <input type="submit" value="Submit">
    </form>

    The following section describes different types of controls that you can use in your form.

    Input Element

    This is the most commonly used element within HTML forms.

    It allows you to specify various types of user input fields, depending on the type attribute. An input element can be of type text fieldpassword fieldcheckboxradio buttonsubmit buttonreset buttonfile select box, as well as several new input types introduced in HTML5.

    The most frequently used input types are described below.

    Text Fields

    Text fields are one line areas that allow the user to input text.

    Single-line text input controls are created using an <input> element, whose type attribute has a value of text. Here’s an example of a single-line text input used to take username:

    Example

    <form>
        <label for="username">Username:</label>
        <input type="text" name="username" id="username">
    </form>

    — The output of the above example will look something like this:

    HTML Text Input Field

    Note: The <label> tag is used to define the labels for <input> elements. If you want your user to enter several lines you should use a <textarea> instead.


    Password Field

    Password fields are similar to text fields. The only difference is; characters in a password field are masked, i.e. they are shown as asterisks or dots. This is to prevent someone else from reading the password on the screen. This is also a single-line text input controls created using an <input> element whose type attribute has a value of password.

    Here’s an example of a single-line password input used to take user password:

    Example

    <form>
        <label for="user-pwd">Password:</label>
        <input type="password" name="user-password" id="user-pwd">
    </form>

    — The output of the above example will look something like this:

    HTML Password Input Field

    Radio Buttons

    Radio buttons are used to let the user select exactly one option from a pre-defined set of options. It is created using an <input> element whose type attribute has a value of radio.

    Here’s an example of radio buttons that can be used to collect user’s gender information:

    Example

    <form>
        <input type="radio" name="gender" id="male">
        <label for="male">Male</label>
        <input type="radio" name="gender" id="female">
        <label for="female">Female</label>
    </form>

    — The output of the above example will look something like this:

    HTML Radio Buttons

    Checkboxes

    Checkboxes allows the user to select one or more option from a pre-defined set of options. It is created using an <input> element whose type attribute has a value of checkbox.

    Here’s an example of checkboxes that can be used to collect information about user’s hobbies:

    Example

    <form>
        <input type="checkbox" name="sports" id="soccer">
        <label for="soccer">Soccer</label>
        <input type="checkbox" name="sports" id="cricket">
        <label for="cricket">Cricket</label>
        <input type="checkbox" name="sports" id="baseball">
        <label for="baseball">Baseball</label>
    </form>

    — The output of the above example will look something like this:

    HTML Checkboxes

    Note: If you want to make a radio button or checkbox selected by default, you can add the attribute checked to the input element, like <input type="checkbox" checked>.


    File Select box

    The file fields allow a user to browse for a local file and send it as an attachment with the form data. Web browsers such as Google Chrome and Firefox render a file select input field with a Browse button that enables the user to navigate the local hard drive and select a file.

    This is also created using an <input> element, whose type attribute value is set to file.

    Example

    <form>
        <label for="file-select">Upload:</label>
        <input type="file" name="upload" id="file-select">
    </form>

    — The output of the above example will look something like this:

    HTML File Select Field

    Tip: There are several other input types. Please check out the chapter on HTML5 new input types to learn more about the newly introduced input types.


    Textarea

    Textarea is a multiple-line text input control that allows a user to enter more than one line of text. Multi-line text input controls are created using an <textarea> element.

    Example

    <form>
        <label for="address">Address:</label>
        <textarea rows="3" cols="30" name="address" id="address"></textarea>
    </form>

    — The output of the above example will look something like this:

    HTML Textarea

    Select Boxes

    A select box is a dropdown list of options that allows user to select one or more option from a pull-down list of options. Select box is created using the <select> element and <option> element.

    The <option> elements within the <select> element define each list item.

    Example

    <form>
        <label for="city">City:</label>
        <select name="city" id="city">
            <option value="sydney">Sydney</option>
            <option value="melbourne">Melbourne</option>
            <option value="cromwell">Cromwell</option>
        </select>
    </form>

    — The output of the above example will look something like this:

    HTML Select Dropdown

    Submit and Reset Buttons

    A submit button is used to send the form data to a web server. When submit button is clicked the form data is sent to the file specified in the form’s action attribute to process the submitted data.

    A reset button resets all the forms control to default values. Try out the following example by typing your name in the text field, and click on submit button to see it in action.

    Example

    <form action="action.php" method="post">
        <label for="first-name">First Name:</label>
        <input type="text" name="first-name" id="first-name">
        <input type="submit" value="Submit">
        <input type="reset" value="Reset">
    </form>
    HTML Submit and Reset Buttons

    Type your name in the text field above, and click on submit button to see it in action.

    Note: You can also create buttons using the <button> element. Buttons created with the <button> element function just like buttons created with the input element, but they offer richer rendering possibilities by allowing the embedding of other HTML elements.


    Grouping Form Controls

    You also group logically related controls and labels within a web form using the <legend> element. Grouping form controls into categories makes it easier for users to locate a control which makes the form more user-friendly. Let’s try out the following example to see how it works:

    Example

    <form>
        <fieldset>
            <legend>Contact Details</legend>
            <label>Email Address: <input type="email" name="email"></label>
            <label>Phone Number: <input type="text" name="phone"></label>
        </fieldset>
    </form>

    Frequently Used Form Attributes

    The following table lists the most frequently used form element’s attributes:

    AttributeDescription
    nameSpecifies the name of the form.
    actionSpecifies the URL of the program or script on the web server that will be used for processing the information submitted via form.
    methodSpecifies the HTTP method used for sending the data to the web server by the browser. The value can be either get (the default) and post.
    targetSpecifies where to display the response that is received after submitting the form. Possible values are _blank_self_parent and _top.
    enctypeSpecifies how the form data should be encoded when submitting the form to the server. Applicable only when the value of the method attribute is post.

    There are several other attributes, to know about them please see the <form> tag reference.

  • HTML Lists

    Working with HTML Lists

    HTML lists are used to present list of information in well formed and semantic way. There are three different types of list in HTML and each one has a specific purpose and meaning.

    • Unordered list — Used to create a list of related items, in no particular order.
    • Ordered list — Used to create a list of related items, in a specific order.
    • Description list — Used to create a list of terms and their descriptions.

    Note: Inside a list item you can put text, images, links, line breaks, etc. You can also place an entire list inside a list item to create the nested list.

    In the following sections we will cover all the three types of list one by one:

    HTML Unordered Lists

    An unordered list created using the <ul> element, and each list item starts with the <li> element.

    The list items in unordered lists are marked with bullets. Here’s an example:

    Example

    <ul>
        <li>Chocolate Cake</li>
        <li>Black Forest Cake</li>
        <li>Pineapple Cake</li>
    </ul>

    — The output of the above example will look something like this:

    • Chocolate Cake
    • Black Forest Cake
    • Pineapple Cake

    You can also change the bullet type in your unordered list using the CSS list-style-type property. The following style rule changes the type of bullet from the default disc to square:

    Example

    ul {
        list-style-type: square;
    }

    Please check out the tutorial on CSS lists to learn about styling HTML lists in details.


    HTML Ordered Lists

    An ordered list created using the <ol> element, and each list item starts with the <li> element. Ordered lists are used when the order of the list’s items is important.

    The list items in an ordered list are marked with numbers. Here’s an example:

    Example

    <ol>
        <li>Fasten your seatbelt</li>
        <li>Starts the car's engine</li>
        <li>Look around and go</li>
    </ol>

    — The output of the above example will look something like this:

    1. Fasten your seatbelt
    2. Starts the car’s engine
    3. Look around and go

    The numbering of items in an ordered list typically starts with 1. However, if you want to change that you can use the start attribute, as shown in the following example:

    Example

    <ol start="10">
        <li>Mix ingredients</li>
        <li>Bake in oven for an hour</li>
        <li>Allow to stand for ten minutes</li>
    </ol>

    — The output of the above example will look something like this:

    1. Mix ingredients
    2. Bake in oven for an hour
    3. Allow to stand for ten minutes

    Like unordered list, you can also use the CSS list-style-type property to change the numbering type in an ordered list. The following style rule changes the marker type to roman numbers.

    Example

    ol {
        list-style-type: upper-roman;
    }

    Tip: You can also use the type attribute to change the numbering type e.g. type="I". However, you should avoid this attribute, use the CSS list-style-type property instead.


    HTML Description Lists

    A description list is a list of items with a description or definition of each item.

    The description list is created using <dl> element. The <dl> element is used in conjunction with the <dt> element which specify a term, and the <dd> element which specify the term’s definition.

    Browsers usually render the definition lists by placing the terms and definitions in separate lines, where the term’s definitions are slightly indented. Here’s an example:

    Example

    <dl>
        <dt>Bread</dt>
        <dd>A baked food made of flour.</dd>
        <dt>Coffee</dt>
        <dd>A drink made from roasted coffee beans.</dd>
    </dl>
    

    — The output of the above example will look something like this:BreadA baked food made of flour.CoffeeA drink made from roasted coffee beans.