Author: Saim Khalid

  • 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.

  • HTML Tables

    Creating Tables in HTML

    HTML table allows you to arrange data into rows and columns. They are commonly used to display tabular data like product listings, customer’s details, financial reports, and so on.

    You can create a table using the <table> element. Inside the <table> element, you can use the <tr> elements to create rows, and to create columns inside a row you can use the <td> elements. You can also define a cell as a header for a group of table cells using the <th> element.

    The following example demonstrates the most basic structure of a table.

    Example

    <table>
        <tr>
            <th>No.</th>
            <th>Name</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>1</td>
            <td>Peter Parker</td>
            <td>16</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Clark Kent</td>
            <td>34</td>
        </tr>
    </table>
    
    

    Tables do not have any borders by default. You can use the CSS border property to add borders to the tables. Also, table cells are sized just large enough to fit the contents by default. To add more space around the content in the table cells you can use the CSS padding property.

    The following style rules add a 1-pixel border to the table and 10-pixels of padding to its cells.

    Example

    table, th, td {
        border: 1px solid black;
    }
    th, td {
        padding: 10px;
    }

    By default, borders around the table and their cells are separated from each other. But you can collapse them into one by using the border-collapse property on the <table> element.

    Also, text inside the <th> elements are displayed in bold font, aligned horizontally center in the cell by default. To change the default alignment you can use the CSS text-align property.

    The following style rules collapse the table borders and align the table header text to left.

    Example

    table {
        border-collapse: collapse;
    }
    th {
        text-align: left;
    }

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

    Note: Most of the <table> element’s attribute such as bordercellpaddingcellspacingwidthalign, etc. for styling table appearances in earlier versions has been dropped in HTML5, so avoid using them. Use CSS to style HTML tables instead.


    Spanning Multiple Rows and Columns

    Spanning allow you to extend table rows and columns across multiple other rows and columns.

    Normally, a table cell cannot pass over into the space below or above another table cell. But, you can use the rowspan or colspan attributes to span multiple rows or columns in a table.

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

    Example

    <table>
        <tr>
            <th>Name</th>
            <th colspan="2">Phone</th>
        </tr>
        <tr>
            <td>John Carter</td>
            <td>5550192</td>
            <td>5550152</td>
        </tr>
    </table>

    Similarly, you can use the rowspan attribute to create a cell that spans more than one row. Let’s try out an example to understand how row spanning basically works:

    Example

    <table>
        <tr>
            <th>Name:</th>
            <td>John Carter</td>
        </tr>
        <tr>
            <th rowspan="2">Phone:</th>
            <td>55577854</td>
        </tr>
        <tr>
            <td>55577855</td>
        </tr>
    </table>

    Adding Captions to Tables

    You can specify a caption (or title) for your tables using the <caption> element.

    The <caption> element must be placed directly after the opening <table> tag. By default, caption appears at the top of the table, but you can change its position using the CSS caption-side property.

    The following example shows how to use this element in a table.

    Example

    <table>
        <caption>Users Info</caption>
        <tr>
            <th>No.</th>
            <th>Name</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>1</td>
            <td>Peter Parker</td>
            <td>16</td>
        </tr>
        <tr>
            <td>2</td>
            <td>Clark Kent</td>
            <td>34</td>
        </tr>
    </table>

    Defining a Table Header, Body, and Footer

    HTML provides a series of tags <thead><tbody>, and <tfoot> that helps you to create more structured table, by defining header, body and footer regions, respectively.

    The following example demonstrates the use of these elements.

    Example

    <table>
        <thead>
            <tr>
                <th>Items</th>
                <th>Expenditure</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Stationary</td>
                <td>2,000</td>
            </tr>
            <tr>
                <td>Furniture</td>
                <td>10,000</td>
            </tr>        
        </tbody>
        <tfoot>
            <tr>
                <th>Total</th>
                <td>12,000</td>
            </tr>
        </tfoot>
    </table>
  • HTML Images

    Inserting Images into Web Pages

    Images enhance visual appearance of the web pages by making them more interesting and colorful.

    The <img> tag is used to insert images in the HTML documents. It is an empty element and contains attributes only. The syntax of the <img> tag can be given with:

    <img src=”url” alt=”some_text“>

    The following example inserts three images on the web page:

    Example

    <img src="kites.jpg" alt="Flying Kites">
    <img src="sky.jpg" alt="Cloudy Sky">
    <img src="balloons.jpg" alt="Balloons">

    Each image must carry at least two attributes: the src attribute, and an alt attribute.

    The src attribute tells the browser where to find the image. Its value is the URL of the image file.

    Whereas, the alt attribute provides an alternative text for the image, if it is unavailable or cannot be displayed for some reason. Its value should be a meaningful substitute for the image.

    Note: Like <br> , the <img> element is also an empty element, and does not have a closing tag. However, in XHTML it closes itself ending with “/>“.

    Tip: The required alt attribute provides alternative text description for an image if a user for some reason cannot able to view it because of slow connection, image is not available at the specified URL, or if the user uses a screen reader or non-graphical browser.


    Setting the Width and Height of an Image

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

    The values of these attributes are interpreted in pixels by default.

    Example

    <img src="kites.jpg" alt="Flying Kites" width="300" height="300">
    <img src="sky.jpg" alt="Cloudy Sky" width="250" height="150">
    <img src="balloons.jpg" alt="Balloons" width="200" height="200">

    You can also use the style attribute to specify width and height for the images. It prevents style sheets from changing the image size accidently, since inline style has the highest priority.

    Example

    Try this code »

    <img src="kites.jpg" alt="Flying Kites" style="width: 300px; height: 300px;">
    <img src="sky.jpg" alt="Cloudy Sky" style="width: 250px; height: 150px;">
    <img src="balloons.jpg" alt="Balloons" style="width: 200px; height: 200px;">

    Note: It’s a good practice to specify both the width and height attributes for an image, so that browser can allocate that much of space for the image before it is downloaded. Otherwise, image loading may cause distortion or flicker in your website layout.


    Using the HTML5 Picture Element

    Sometimes, scaling an image up or down to fit different devices (or screen sizes) doesn’t work as expected. Also, reducing the image dimension using the width and height attribute or property doesn’t reduce the original file size. To address these problems HTML5 has introduced the <picture> tag that allows you to define multiple versions of an image to target different types of devices.

    The <picture> element contains zero or more <source> elements, each referring to different image source, and one <img> element at the end. Also each <source> element has the media attribute which specifies a media condition (similar to the media query) that is used by the browser to determine when a particular source should be used. Let’s try out an example:

    Example

    <picture>
        <source media="(min-width: 1000px)" srcset="logo-large.png">
        <source media="(max-width: 500px)" srcset="logo-small.png">
        <img src="logo-default.png" alt="My logo">
    </picture>

    Note: The browser will evaluate each child <source> element and choose the best match among them; if no matches are found, the URL of the <img> element’s src attribute is used. Also, the <img> tag must be specified as the last child of the <picture> element.


    Working with Image Maps

    An image map allows you to define hotspots on an image that acts just like a hyperlink.

    The basic idea behind creating image map is to provide an easy way of linking various parts of an image without dividing it into separate image files. For example, a map of the world may have each country hyperlinked to further information about that country.

    Let’s try out a simple example to understand how it actually works:

    Example

    <img src="objects.png" usemap="#objects" alt="Objects">
    <map name="objects">
        <area shape="circle" coords="137,231,71" href="clock.html" alt="Clock">
        <area shape="poly" coords="363,146,273,302,452,300" href="sign.html" alt="Sign">
        <area shape="rect" coords="520,160,641,302" href="book.html" alt="Book">
    </map>

    The name attribute of the <map> tag is used to reference the map from the <img> tag using its usemap attribute. The <area> tag is used inside the <map> element to define the clickable areas on an image. You can define any number of clickable areas within an image.

  • HTML Styles

    Styling HTML Elements

    HTML is quite limited when it comes to the presentation of a web page. It was originally designed as a simple way of presenting information. CSS (Cascading Style Sheets) was introduced in December 1996 by the World Wide Web Consortium (W3C) to provide a better way to style HTML elements.

    With CSS, it becomes very easy to specify the things like, size and typeface for the fonts, colors for the text and backgrounds, alignment of the text and images, amount of space between the elements, border and outlines for the elements, and lots of other styling properties.

    Adding Styles to HTML Elements

    Style information can either be attached as a separate document or embedded in the HTML document itself. These are the three methods of implementing styling information to an HTML document.

    • Inline styles — Using the style attribute in the HTML start tag.
    • Embedded style — Using the <style> element in the head section of the document.
    • External style sheet — Using the <link> element, pointing to an external CSS files.

    In this tutorial we will cover all these different types of style sheet one by one.

    Note: The inline styles have the highest priority, and the external style sheets have the lowest. It means if you specify styles for your paragraphs in both embedded and external style sheets, the conflicting style rules in the embedded style sheet would override the external style sheet.

    Inline Styles

    Inline styles are used to apply the unique style rules to an element, by putting the CSS rules directly into the start tag. It can be attached to an element using the style attribute.

    The style attribute includes a series of CSS property and value pairs. Each property: value pair is separated by a semicolon (;), just as you would write into an embedded or external style sheet. But it needs to be all in one line i.e. no line break after the semicolon.

    The following example demonstrates how to set the color and font-size of the text:

    Example

    <h1 style="color:red; font-size:30px;">This is a heading</h1>
    <p style="color:green; font-size:18px;">This is a paragraph.</p>
    <div style="color:green; font-size:18px;">This is some text.</div>

    Using the inline styles are generally considered as a bad practice. Because style rules are embedded directly inside the html tag, it causes the presentation to become mixed with the content of the document, which makes updating or maintaining a website very difficult.

    To learn about the various CSS properties in detail, please check out CSS tutorial section.

    Note: It’s become impossible to style pseudo-elements and pseudo-classes with inline styles. You should, therefore, avoid the use of style attributes in your markup. Using external style sheet is the preferred way to add style information to an HTML document.


    Embedded Style Sheets

    Embedded or internal style sheets only affect the document they are embedded in.

    Embedded style sheets are defined in the <head> section of an HTML document using the <style> tag. You can define any number of <style> elements inside the <head> section.

    The following example demonstrates how style rules are embedded inside a web page.

    Example

    <head>
        <style>
            body { background-color: YellowGreen; }
    		h1 { color: blue; }
            p { color: red; }
        </style>
    </head>

    External Style Sheets

    An external style sheet is ideal when the style is applied to many pages.

    An external style sheet holds all the style rules in a separate document that you can link from any HTML document on your site. External style sheets are the most flexible because with an external style sheet, you can change the look of an entire website by updating just one file.

    You can attach external style sheets in two ways — linking and importing:

    Linking External Style Sheets

    An external style sheet can be linked to an HTML document using the <link> tag.

    The <link> tag goes inside the <head> section, as shown here:

    Example

    <head>
        <link rel="stylesheet" href="css/style.css">
    </head>

    Importing External Style Sheets

    The @import rule is another way of loading an external style sheet. The @import statement instructs the browser to load an external style sheet and use its styles.

    You can use it in two ways. The simplest way is to use it within the <style> element in your <head> section. Note that, other CSS rules may still be included in the <style> element.

    Example

    <style>
        @import url("css/style.css");
        p {
            color: blue;
            font-size: 16px;
        }
    </style>

    Similarly, you can use the @import rule to import a style sheet within another style sheet.

    Example

    @import url("css/layout.css");
    @import url("css/color.css");
    body {
        color: blue;
        font-size: 14px;
    }
  • HTML Text Formatting

    Formatting Text with HTML

    HTML provides several tags that you can use to make some text on your web pages to appear differently than normal text, for example, you can use the tag <b> to make the text bold, tag <i> to make the text italic, tag <mark> to highlight the text, tag <code> to display a fragment of computer code, tags <ins> and <del> for marking editorial insertions and deletions, and more.

    The following example demonstrates the most commonly used formatting tags in action. Now, let’s try this out to understand how these tags basically work:

    Example

    <p>This is <b>bold text</b>.</p>
    <p>This is <strong>strongly important text</strong>.</p>
    <p>This is <i>italic text</i>.</p>
    <p>This is <em>emphasized text</em>.</p>
    <p>This is <mark>highlighted text</mark>.</p>
    <p>This is <code>computer code</code>.</p>
    <p>This is <small>smaller text</small>.</p>
    <p>This is <sub>subscript</sub> and <sup>superscript</sup> text.</p>
    <p>This is <del>deleted text</del>.</p>
    <p>This is <ins>inserted text</ins>.</p>

    By default, the <strong> tag is typically rendered in the browser as <b>, whereas the <em> tag is rendered as <i>. However, there is a difference in the meaning of these tags.

    Difference between <strong> and <b> tag

    Both <strong> and <b> tags render the enclosed text in a bold typeface by default, but the <strong> tag indicates that its contents have strong importance, whereas the <b> tag is simply used to draw the reader’s attention without conveying any special importance.

    Example

    <p><strong>WARNING!</strong> Please proceed with caution.</p>
    <p>The concert will be held at <b>Hyde Park</b> in London.</p>

    Difference between <em> and <i> tag

    Similarly, both <em> and <i> tags render the enclosed text in italic type by default, but the <em> tag indicates that its contents have stressed emphasis compared to surrounding text, whereas the <i> tag is used for marking up text that is set off from the normal text for readability reasons, such as a technical term, an idiomatic phrase from another language, a thought, etc.

    Example

    <p>Cats are <em>cute</em> animals.</p>
    <p>The <i>Royal Cruise</i> sailed last night.</p>

    Note: Use the <em> and <strong> tags when the content of your page requires that certain words or phrases should have strong emphasis or importance. Also, in HTML5 the <b> and <i> tags have been redefined, earlier they don’t have semantic meaning.


    Formatting Quotations

    You can easily format the quotation blocks from other sources with the HTML <blockquote> tag.

    Blockquotes are generally displayed with indented left and right margins, along with a little extra space added above and below. Let’s try an example to see how it works:

    Example

    <blockquote>
        <p>Learn from yesterday, live for today, hope for tomorrow. The important thing is not to stop questioning.</p>
        <cite>— Albert Einstein</cite>
    </blockquote>

    Tip: The cite tag is used to describe a reference to a creative work. It must include the title of that work or the name of the author (people or organization) or an URL reference.

    For short inline quotations, you can use the HTML <q> tag. Most browsers display inline quotes by surrounding the text in quotation marks. Here’s an example:

    Example

    <p>According to the World Health Organization (WHO): <q>Health is a state of complete physical, mental, and social well-being.</q></p>

    Showing Abbreviations

    An abbreviation is a shortened form of a word, phrase, or name.

    You can use the <abbr> tag to denote an abbreviation. The title attribute is used inside this tag to provide the full expansion of the abbreviation, which is displayed by the browsers as a tooltip when the mouse cursor is hovered over the element. Let’s try out an example:

    Example

    <p>The <abbr title="World Wide Web Consortium">W3C</abbr> is the main international standards organization for the <abbr title="World Wide Web">WWW or W3</abbr>. It was was founded by Tim Berners-Lee.</p>

    Marking Contact Addresses

    Web pages often include street or postal addresses. HTML provides a special tag <address> to represent contact information (physical and/or digital) for a person, people or organization.

    This tag should ideally used to display contact information related to the document itself, such as article’s author. Most browsers display an address block in italic. Here’s an example:

    Example

    <address>
    Mozilla Foundation<br>
    331 E. Evelyn Avenue<br>
    Mountain View, CA 94041, USA
    </address>
  • HTML Links

    Creating Links in HTML

    A link or hyperlink is a connection from one web resource to another. Links allow users to move seamlessly from one page to another, on any server anywhere in the world.

    A link has two ends, called anchors. The link starts at the source anchor and points to the destination anchor, which may be any web resource, for example, an image, an audio or video clip, a PDF file, an HTML document or an element within the document itself, and so on.

    By default, links will appear as follows in most of the browsers:

    • An unvisited link is underlined and blue.
    • A visited link is underlined and purple.
    • An active link is underlined and red.

    However, you can overwrite this using CSS. Learn more about styling links.

    HTML Link Syntax

    Links are specified in HTML using the <a> tag.

    A link or hyperlink could be a word, group of words, or image.

    <a href=”url“>Link text</a>

    Anything between the opening <a> tag and the closing </a> tag becomes the part of the link that the user sees and clicks in a browser. Here are some examples of the links:

    Example

    <a href="https://www.google.com/">Google Search</a>
    <a href="https://www.tutorialrepublic.com/">Tutorial Republic</a>
    <a href="images/kites.jpg">
        <img src="kites-thumb.jpg" alt="kites">
    </a>

    The href attribute specifies the target of the link. Its value can be an absolute or relative URL.

    An absolute URL is the URL that includes every part of the URL format, such as protocol, host name, and path of the document, e.g., https://www.google.com/https://www.example.com/form.php, etc. While, relative URLs are page-relative paths, e.g., contact.htmlimages/smiley.png, and so on. A relative URL never includes the http:// or https:// prefix.


    Setting the Targets for Links

    The target attribute tells the browser where to open the linked document. There are four defined targets, and each target name starts with an underscore(_) character:

    • _blank — Opens the linked document in a new window or tab.
    • _parent — Opens the linked document in the parent window.
    • _self — Opens the linked document in the same window or tab as the source document. This is the default, hence it is not necessary to explicitly specify this value.
    • _top — Opens the linked document in the full browser window.

    Try out the following example to understand how the link’s target basically works:

    Example

    <a href="/about-us.php" target="_top">About Us</a>
    <a href="https://www.google.com/" target="_blank">Google</a>
    <a href="images/sky.jpg" target="_parent">
        <img src="sky-thumb.jpg" alt="Cloudy Sky">
    </a>

    Tip: If your web page is placed inside an iframe, you can use the target="_top" on the links to break out of the iframe and show the target page in full browser window.


    Creating Bookmark Anchors

    You can also create bookmark anchors to allow users to jump to a specific section of a web page. Bookmarks are especially helpful if you have a very long web page.

    Creating bookmarks is a two-step process: first add the id attribute on the element where you want to jump, then use that id attribute value preceded by the hash sign (#) as the value of the href attribute of the <a> tag, as shown in the following example:

    Example

    <a href="#sectionA">Jump to Section A</a>
    <h2 id="sectionA">Section A</h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit...</p>

    Tip: You can even jump to a section of another web page by specifying the URL of that page along with the anchor (i.e. #elementId) in the href attribute, for example, <a href="mypage.html#topicA">Go to TopicA</a>.


    Creating Download Links

    You can also create the file download link in exactly the same fashion as placing text links. Just point the destination URL to the file you want to be available for download.

    In the following example we’ve created the download links for ZIP, PDF and JPG files.

    Example

    <a href="downloads/test.zip">Download Zip file</a>
    <a href="downloads/masters.pdf">Download PDF file</a>
    <a href="downloads/sample.jpg">Download Image file</a>