× back

HTML and CSS

HTML

HTML4 vs HTML5

  • HTML4 was the fourth version of the Hypertext Markup Language, and it was introduced in 1997 by the World Wide Web Consortium (W3C). It was widely used during the late 1990s and early 2000s, playing a crucial role in the development of the early web. HTML4 introduced several features that enhanced the capabilities of web pages, including tables for layout, forms, and scripting through JavaScript.
    • Key Features of HTML4:
      1. Introduction of tables for layout purposes.
      2. Support for forms and form elements.
      3. Basic support for scripting through JavaScript.
      4. Limited multimedia support.
      5. Lack of native support for audio and video elements.
      6. Dependency on plugins (like Flash) for rich multimedia content.
  • HTML5 is the fifth and latest version of HTML, introduced by the W3C in 2014. It was designed to address the shortcomings of HTML4 and accommodate the evolving needs of web development. HTML5 introduced new elements, attributes, and APIs, providing better support for multimedia, improved semantics, and enhanced capabilities for creating modern web applications.
    • Key Features of HTML5:
      1. Native support for audio and video elements, reducing dependency on plugins.
      2. New semantic elements (header, nav, article, section, etc.) for improved document structure.
      3. Introduction of the '<canvas>' element for drawing graphics and animations.
      4. Support for offline web applications through the Application Cache.
      5. Improved form controls and validation.
      6. Introduction of the '<svg>' element for scalable vector graphics.
      7. Enhanced accessibility features.

Doctype

  • A Document Type Declaration, or DOCTYPE, is a specific instruction included at the beginning of an HTML document to tell the web browser which version of HTML the document is written in. It helps the browser render the content correctly by following the appropriate rules and specifications.
  • In HTML4, there were three main types of DOCTYPE declarations: Transitional, Strict, and Frameset.
    1. Transitional: In the Transitional era, developers often mixed content and design within HTML, using tags like <center>, <i>, <b>, <u>, and various font-related attributes to control layout and styling. This approach allowed for a smoother transition from older HTML versions, but it encouraged the use of deprecated and presentational elements for styling.
    2. Strict: The Strict DOCTYPE encouraged a cleaner separation of content and presentation. It discouraged the use of deprecated tags and attributes for styling and advocated for the adoption of CSS (Cascading Style Sheets) for layout and design. This approach led to more maintainable and semantically meaningful HTML documents, with styling moved to external CSS files.
    3. Frameset: The Frameset DOCTYPE was designed for creating web pages with frames, a feature that allowed multiple documents to be displayed within a single browser window. Each frame could contain a separate HTML document. Framesets were used for creating layouts with separate areas for navigation, headers, and content. However, frames became less popular due to usability issues, search engine challenges, and the rise of modern layout techniques.
  • HTML5 is often considered equivalent to the strict mode of HTML4. In HTML5, there is a simplified and universal DOCTYPE declaration:
                                
    <!DOCTYPE html>
                                
                            
    • HTML5 marked a significant shift in web development philosophy. It embraced the separation of concerns by recommending a single DOCTYPE (<!DOCTYPE html>) and promoting the use of CSS for styling. HTML5 introduced new semantic elements, like <header>, <nav>, <article>, <section>, and <footer>, which provide more meaningful structure to web documents. Deprecated elements were phased out, and modern features, such as the <iframe> tag for embedding content from other sources, replaced outdated practices like frames.

HTML structure

How to save html file?

Understanding HTML Structure

  • DOCTYPE: It defines the document type and instructs the browser about the HTML version. It is crucial for programmers to identify the HTML version they are using.
  • html tag (<html></html>): This tag informs the browser that it is an HTML document. Text between the html tags describes the web document and serves as the root or container for all other HTML elements, excluding the DOCTYPE.
  • head tag (<head></head>): It should be the first element inside the html tag and contains metadata, which provides information about the document. The head tag must be closed before the body tag opens. Metadata, including title, character set, and linked stylesheets, helps in SEO and proper document interpretation.
  • title tag (<title></title>): Used to add the title of the HTML page, which appears at the top of the browser window. It must be placed inside the head tag and should close immediately. While optional, it is essential for providing a meaningful title for the webpage.
  • body tag (<body></body>): Text between the body tags describes the visible content of the page that is presented to the end user. This tag contains the main content of the HTML document, including text, images, links, and other elements.
  • h1 - h6 tags: These tags are used to display headings of the webpage. h1 has the largest font size, and h6 has the smallest font size. They provide a hierarchy for organizing and structuring the content on the page.
  • p tag (<p></p>): Text between the p tags describes a paragraph of the webpage. It is advisable to place multiple-line statements inside the p tag to ensure proper formatting and semantic structure in the HTML document.

Note: Essentially, HTML is comprised of tags, and these tags are opened and then closed with content or text placed between them. While all HTML tags are not necessarily paired with closing tags, there are two main types of tags in HTML:

  • Paired (Open/Close) Tags: These tags have both an opening and a closing tag, encapsulating content between them. An example is the paragraph tag: <p>Content goes here</p>. The opening tag <p> signifies the beginning of the paragraph, and the closing tag </p> marks the end.
  • Self-Closing Tags: These tags are used when an element doesn't require any content, and they close themselves. An example is the line break tag: <br>. There is no need for a separate closing tag as it self-closes, indicating a line break without any content in between.

Features of HTML

  • Easy and Simple Language: HTML is known for its simplicity, making it easy for beginners to learn and use. Its straightforward syntax and tag-based structure contribute to its accessibility.
  • Effective Presentation: HTML provides a rich set of formatting tags that enable the creation of visually appealing and effective presentations. With tags for headings, paragraphs, lists, images, and more, HTML allows developers to structure content for a compelling user experience.
  • Platform Independence: HTML is platform-independent, meaning it can be rendered and displayed consistently across different operating systems and devices. This universality contributes to its widespread adoption for creating content on the World Wide Web.
  • Case Insensitive: HTML is a case-insensitive language, allowing developers to use uppercase or lowercase letters interchangeably when writing tags. However, for the sake of consistency and readability, it is recommended to write HTML tags in lowercase. This practice ensures uniformity and makes the code more accessible to collaborators and easier to maintain over time.
  • Compatibility: HTML is compatible with other web technologies, such as CSS (Cascading Style Sheets) for styling and JavaScript for dynamic behavior. This interoperability allows developers to create interactive and visually appealing web pages by combining different technologies.
  • Extensibility: HTML is extensible, meaning it can be augmented with additional features and functionalities. Through the use of attributes and custom elements, developers can extend HTML's capabilities to meet specific requirements.
  • Global Adoption: HTML is a globally adopted standard for creating web content. Its widespread use ensures that web pages and applications built with HTML can be accessed and understood by a broad audience worldwide, contributing to the democratization of information on the Internet.
  • Accessibility: HTML provides features and attributes that support accessibility, making web content more inclusive for users with disabilities. Semantic HTML elements, ARIA (Accessible Rich Internet Applications) roles, and attributes enhance the usability of websites and applications for all users.
  • Evolution: HTML is a living standard that evolves over time. The introduction of new versions, such as HTML5, brings enhanced features, improved semantics, and better support for multimedia, keeping HTML at the forefront of modern web development.

img tag

                    
<!DOCTYPE html>
<html> 
    <head><title>...</title></head>
    <body> 
        <img src="path of image" alt="alternate text" width="400px" height="500px" />
        <img src="path of image" alt="alternate text" width="350px" height="350px" />
    </body>
</html>
                    
                
  • HTML img Tag: Used to display images on a webpage. It is an empty tag that contains attributes; closing tags are not used in the HTML img element.

Attributes of HTML img Tag:

  • src: Stands for "source." It is a necessary attribute that specifies the source or path of the image.
    • It instructs the browser to find the image at the given location.
    • The image may be located in the directory or on another server.
  • alt: This alt attribute defines alternate text for the image if it cannot be displayed.
    • The value of the alt attribute is considered good for search engine optimization.
  • width: An optional attribute used to specify the width for displaying the image. It is not recommended; you can apply CSS instead of the width attribute.
  • height: This attribute also supports iframe, image, and object elements. It is not recommended; you can apply CSS instead of the height attribute.

a tag

  • The 'a' tag in HTML is specifically known as the "anchor" tag. The anchor tag is used to create hyperlinks, allowing users to navigate from one page to another or to different sections within the same page.
                    
<!DOCTYPE html> 
<html> 
    <head> 
        <title>web page title</title>
    </head>
    <body> 
        <h1>Hyperlink</h1>
        <a href="url of another page" target="_blank">click me</a>
        <a href="https://www.example.com" target="_self">Visit Example Website</a>
    </body>
</html>
                    
                
  • href Attribute in <a> Tag: The href attribute in the <a> (anchor) tag stores the reference link, enabling users to navigate to different web pages, documents, or resources.
    • It defines the URL or path to the destination resource.
    • It can point to various resources such as web pages, documents, images, or other online content.
    • Commonly used in combination with the anchor tag to create hyperlinks.
  • Target Attribute: The target attribute specifies how the linked resource should be displayed when clicked. Common values include "_blank", "_self", "_parent", and "_top."
    • Using target="_blank" opens the linked resource in a new browser tab or window.
    • Using target="_self" opens the linked resource in the same tab or window.
    • Using target="_parent" opens the linked resource in the parent frame. If the link is inside an iframe, it will open in the parent document.
    • Using target="_top" opens the linked resource in the full body of the window, removing all frames.
    • This attribute enhances user experience by controlling the behavior of link navigation.
  • Types of <a> Tags: There are two main types of anchor tags: internal and external.
    • Internal Links: These links navigate within the same website or document.
      • Example: <a href="#section1">Link to Section 1</a> (navigating to a specific section on the same page).
    • External Links: These links navigate to resources outside the current website or document.
      • Example: <a href="https://www.example.com">Visit Example Website</a> (navigating to an external website).

Ordered lists, unordered lists, and definition lists

Ordered list: An ordered list is used to create a list of items that are sequentially numbered. The items are typically displayed with numbers or letters.

Example code:

                            
<ol>
    <li>First item</li>
    <li>Second item</li>
    <li>Third item</li>
</ol>
                            
                        

output:

  1. First item
  2. Second item
  3. Third item

Unordered list: An unordered list is used to create a list of items that do not have a specific order. The items are typically displayed with bullet points.

Example code:

                    
<ul>
    <li>Item one</li>
    <li>Item two</li>
    <li>Item three</li>
</ul>                        
                    
                

Output:

  • Item one
  • Item two
  • Item three

Definition List: A definition list is used to create a list of terms and their corresponding definitions. It is commonly used for glossaries or descriptions.

Example code:

                            
<dl>
    <dt>HTML</dt>
    <dd>HyperText Markup Language</dd>
    <dt>CSS</dt>
    <dd>Cascading Style Sheets</dd>
    <dt>JavaScript</dt>
    <dd>A programming language for web development</dd>
</dl>

                            
                        

Output:

HTML
HyperText Markup Language
CSS
Cascading Style Sheets
JavaScript
A programming language for web development

Table

  • The <table> tag is used in HTML to create a structured table for organizing data.
  • Tags used inside the <table> tag:
    • <tr>: Stands for "table row" and is used to define a row within the table.
    • <th>: Stands for "table header" and is used to define header cells within a table row. Typically placed within a <thead> section.
    • <td>: Stands for "table data" and is used to define standard cells within a table row. Typically placed within a <tbody> section.
  • colspan and rowspan Attributes: These attributes are used in conjunction with the <td> (table data) or <th> (table header) elements to control the spanning of columns (colspan) or rows (rowspan) in a table.
    • colspan: This attribute defines the number of columns a cell should span horizontally. It allows a cell to extend across multiple adjacent columns within a single row.
      • Example: <td>Spanning Two Columns</td> (This cell spans two columns in the same row.)
    • rowspan: This attribute defines the number of rows a cell should span vertically. It allows a cell to extend across multiple adjacent rows within a single column.
      • Example: <td rowspan="3">Spanning Three Rows</td> (This cell spans three rows in the same column.)
  • cellspacing and cellpadding: These are attributes traditionally used in HTML tables to control the visual spacing and padding within table cells.
    • cellspacing: This attribute defines the space between adjacent cells in a table. It sets the gap between cells, allowing for better visual separation.
      • Example: <table cellspacing="10"> ... </table> (Defines a spacing of 10 pixels between cells.)
    • cellpadding: This attribute sets the padding within each cell, creating space between the content and the cell border.
      • Example: <table cellpadding="5"> ... </table> (Adds a padding of 5 pixels within each cell.)
    Note: While cellspacing and cellpadding were commonly used in the past, it is recommended to use CSS for styling tables in modern web development.

Creating a simple table structure

movie
data
Movie name Movie cast IMDB Rating
Ephemeral Echoes James Anderson Emily Thompson 8.2
Whispers in the Mist Daniel Rodriguez Olivia Harris 7.9
Serenade of Shadows Michael Turne Sophia Walker 8.5
                    
<!-- Table Code -->
<table border="1px" cellspacing="2" cellpadding="10">
    <tr>
        <th rowspan="4">movie <br> data</th>
        <th>Movie name</th>
        <th colspan="2">Movie cast</th>
        <th>IMDB Rating</th>
    </tr>
    <tr>
        <td>Ephemeral Echoes</td>
        <td>James Anderson</td>
        <td>Emily Thompson</td>
        <td>8.2</td>
    </tr>
    <tr>
        <td>Whispers in the Mist</td>
        <td>Daniel Rodriguez</td>
        <td>Olivia Harris</td>
        <td>7.9</td>
    </tr>
    <tr>
        <td>Serenade of Shadows</td>
        <td>Michael Turner</td>
        <td>Sophia Walker</td>
        <td>8.5</td>
    </tr>
</table>
                    
                

HTML Forms

  • HTML forms provide a user interface for collecting data from users, enabling the input and submission of information to a server or another destination.
  • Different tags used :
    • form: The main container for all form elements. It is used to define the start and end of the form.
    • label: This tag is used to associate a label with form elements, providing a user-friendly description for better accessibility and clarity.
    • input (text): Used for single-line text input fields where users can type alphanumeric characters.
    • input (radio): Represents a radio button, allowing users to select one option from a group of options.
    • input (checkbox): Represents a checkbox, enabling users to select multiple options from a list of choices.
    • select: Creates a dropdown menu, and it is often used with the nested option tag to define individual options within the menu.
    • textarea: Provides a multi-line text input field, suitable for longer text entries or paragraphs.
    • input (password): Similar to the text input, but it conceals the entered characters, commonly used for password input.
    • input (submit): Creates a submit button, which users can click to send the form data to the server.
    • input (reset): Creates a reset button, allowing users to reset the form fields to their default values.
    • input (file): Enables users to upload files through the form, typically used for file submissions.
    • input (number): Provides a numeric input field, often used for numerical data entry with options for setting minimum and maximum values.
    • input (date): Allows users to select a date from a calendar input, useful for date-related information.
    • input (email): Validates that the entered text is in an email format, commonly used for email address input.
    • input (url): Validates that the entered text is in a URL format, often used for website address input.

Creating a login page



Remember me
                    
<form action="#" method="get">
    <label>Username :</label>
    <input type="text" name="uname" required>
    <br>
    <label>Password :</label>
    <input type="password" name="pass" placeholder="Enter password" required>
    <br>
    <button type="submit">Login</button>
    <input type="reset" value="Reset">
    <input type="checkbox" checked="checked">Remember me
</form>  
                    
                

Understanding the Above Code:

  • action="": This attribute specifies where the form data will be sent when the submit button is clicked. The value can be a URL or an empty string for the current page.
  • method: The "method" attribute defines how the form data will be transferred. There are two main types:
    • GET: Data is appended to the URL, visible in the address bar. Suitable for non-sensitive data.
    • POST: Data is sent in the request body, not visible in the URL. Suitable for sensitive or large amounts of data.
  • name attribute in input: The "name" attribute associates a name with an input field, making it possible to reference and collect data from that specific input when the form is submitted.
  • required attribute: When added to an input field, the "required" attribute ensures that the user must fill in that field before submitting the form. It helps enforce mandatory information.
  • placeholder: The "placeholder" attribute provides a hint or prewritten text inside an input field, giving users guidance on what information is expected.

Creating a Registration Page





Male
Female





                    
<form action="#" method="post" class="formdiv">
    <label>First name :</label>
    <input type="text" name="fname" required>
    <br>
    <label>Last name :</label>
    <input type="text" name="lname" required>
    <br>
    <label>Course :</label>
    <select name="course">
        <option value="bca">BCA</option>
        <option value="mca">MCA</option>
    </select>
    <br>
    <label>Gender :</label>
    <br>
    <input type="radio" name="gen" value="male">Male <br>
    <input type="radio" name="gen" value="female">Female <br>
    <label>Address :</label><br>
    <textarea name="address" cols="30" rows="10">Jilla - Nainital</textarea>
    <br>
    <label>Email :</label>
    <input type="email" name="email" required>
    <br>
    <label>Password :</label>
    <input type="password" name="pass" required>
    <br>
    <label>Retype Password :</label>
    <input type="password" name="repass">
    <br>
    <input type="button" value="Submit">
</form>
                    
                

HTML Frames

  • HTML frames are utilized to partition your browser window into multiple sections, each capable of loading a separate HTML document.
  • A collection of frames in the browser window is known as a frameset.
  • The window is divided into frames in a similar way to how tables are organized into rows and columns.
  • The `frameset` is a container tag within which `frame` tags are utilized to define individual frames.
  • If you want to divide the page into rows, you can use the `rows` attribute. For example: <frameset rows="10%, 80%, 10%"></frameset> This creates three frame sections inside the frameset, occupying 10%, 80%, and 10% of the window height, respectively. You can also use the `cols` attribute for column division.
  • To handle scenarios where frames are not supported by the browser, the `noframes` tag can be used. This tag allows displaying alternative text when frames are not supported.
  • Framesets are supported in HTML4 but not in HTML5. Instead, HTML5 introduces the `iframe` element to achieve similar functionalities.
                                    
<!DOCTYPE html>
<html>

<head>
    <title>Document</title>
</head>

<frameset rows="30%, 40%, 30%">
    <frame name="frame1" src="./page1.html"> <!-- These are separate html file located in the same location -->
    <frame name="frame2" src="./page2.html">
    <frame name="frame3" src="./page3.html">
    <noframes>
        <body>
            <h1>Your browser does not support frames</h1>
        </body>
    </noframes>
</frameset>

</html>
                                    
                            
Demo Page ⇒

CSS

Methods for Embedding CSS in an HTML Document

  1. Inline CSS: Inline CSS is applied directly within the HTML tags using the style attribute. This method is useful for styling specific elements on a single page.
  2. Internal CSS: Internal CSS is defined within the HTML document itself, typically in the head section. This approach allows for styling multiple elements across the entire page without the need for an external file.
  3. External CSS: External CSS involves creating a separate CSS file and linking it to the HTML document. This method promotes better organization and maintainability, as the styles can be reused across multiple pages by linking to the same external CSS file.

Inline and Internal CSS are contained within a single HTML file, while External CSS utilizes two separate files: one HTML file and another dedicated CSS file. To link these files, the HTML document includes a link tag in the head section, specifying the path to the external CSS file. This separation of concerns enhances code modularity and simplifies the process of making consistent style changes across multiple pages.

Inline CSS

  • When to Use Inline CSS: Inline CSS is employed when styling specific elements within an HTML document. Here are common scenarios for using inline CSS:
    • Individual Element Styling: When you want to apply unique styles to a particular element, such as changing the color or font size of a specific piece of text.
    • Quick Styling: For rapid styling adjustments without the need for a separate CSS file, especially when dealing with small-scale or one-off styling modifications.
    • Testing or Prototyping: During the initial stages of development, inline CSS can be convenient for quick testing and prototyping before finalizing the overall styling structure.
  • Considerations Regarding Inline CSS: While it is generally advised to avoid the extensive use of inline CSS for larger projects, there are situations where its judicious application can be acceptable or even advantageous.
                         class="language-html"
<!DOCTYPE html> 
<html> 
    <head><title>Inline CSS</title></head>
    <body> 
        <h1 style="color: red; margin-left: 40px;"> Heading </h1>
        <p>Paragraph Content</p>
    </body>
</html>
                        
                    
  • Application of Inline CSS using the Style Attribute: When employing inline CSS, the `style` attribute is utilized on HTML tags to apply specific styles directly to individual elements. The syntax for using the `style` attribute follows a specific pattern:
  •                         
    <tagname style="property: value;">Content</tagname>
                            
                        
    • Example: To change the color of a paragraph text to red, the syntax would be:
    •                         
      <p style="color: red;">This is a red paragraph.</p>
                              
                              
  • Advantages of Inline CSS:
    • Convenience for Quick Styling: Inline CSS can be convenient for rapidly applying styles to specific elements within an HTML document without the need for an external stylesheet, making it suitable for quick prototyping or testing.
  • Disadvantages of Inline CSS:
    • Uniform Styling Challenge: When every element shares the same design, using inline CSS for each element can lead to redundancy and decreased maintainability.
    • Non-reusability: Styles defined inline cannot be easily reused across multiple elements or pages, resulting in increased effort for consistency.
    • Difficult Editing: Managing and editing styles becomes challenging as they are stored in a single location within the HTML, making it harder to maintain and modify.
    • Limited Selectors: Applying styles to pseudo-classes or complex selectors is not feasible with inline CSS, limiting the range of styling possibilities.
    • No Browser Cache Advantage: Inline CSS lacks the benefit of browser caching, meaning that the styles are not cached by the browser for future use, potentially affecting page loading performance.

Internal CSS

  • Definition: Internal CSS refers to the method of applying styles to an HTML document by including the styles within the `<style>` element in the document's `<head>` section. This approach allows for centralized styling that affects multiple elements throughout the entire HTML document.
  • When to Use Internal CSS: Internal CSS is suitable for scenarios where a consistent style is desired across multiple elements or pages within the same HTML document. Here are key considerations:
    • Uniform Styling: When you want to maintain a consistent design for various elements throughout the document.
    • Moderate-sized Projects: For projects that are larger than a single page but don't necessitate an external stylesheet, internal CSS provides a balance between organization and simplicity.
    • Quick Styling Adjustments: When you need to make rapid styling changes without the need for a separate external CSS file.
                         class="language-html"
<!DOCTYPE html>
<html>
    <head>
        <title>Internal CSS</title>
        <style>
            h1 {
                color: blue;
                margin-left: 40px;
            }
            p {
                font-size: 16px;
            }
        </style>
    </head>
    <body>
        <h1>Heading</h1>
        <p>Paragraph Content</p>
    </body>
</html>
                        
                    
  • Advantages of Internal CSS:
    • Centralized Styling: Internal CSS allows for organized and centralized styling, making it easier to manage and maintain styles across multiple elements within the same HTML document.
    • Reuse of Styles: Styles defined internally can be reused throughout the document, promoting consistency and reducing redundancy in code.
    • Moderate Project Flexibility: Internal CSS strikes a balance between the simplicity of inline styling and the external organization of stylesheets, making it suitable for moderate-sized projects.
  • Disadvantages of Internal CSS:
    • Not Ideal for Large Projects: For extensive projects with multiple HTML pages, using internal CSS might lead to code duplication and decreased maintainability. In such cases, external stylesheets are recommended.

External CSS

  • Definition: External CSS involves creating a separate CSS file that contains all the styles for an HTML document. The HTML document then links to this external stylesheet, allowing for a centralized and reusable approach to styling across multiple pages.
  • When to Use External CSS: External CSS is recommended for projects with multiple HTML pages or when a consistent style needs to be applied across various web pages. Key considerations include:
    • Consistency Across Pages: When you want a unified design and style applied consistently to multiple HTML pages.
    • Larger Projects: For extensive projects with numerous pages, external CSS provides a modular and organized way to manage styles, reducing redundancy and improving maintainability.
    • Easy Updates: External stylesheets allow for easy updates and changes to the styling without modifying individual HTML files.
        
/* styles.css */
h1 {
    color: green;
    margin-left: 40px;
}

p {
    font-size: 18px;
}
        
    
                         class="language-html"
<!-- index.html -->
<!DOCTYPE html>
<html>
    <head>
        <title>External CSS</title>
        <link rel="stylesheet" type="text/css" href="styles.css">
    </head>
    <body>
        <h1>Heading</h1>
        <p>Paragraph Content</p>
    </body>
</html>
                    
                
  • Advantages of External CSS:
    • Modularity and Reusability: External CSS promotes modularity by separating styles from HTML, making it easy to reuse the same stylesheet across multiple pages for consistent styling.
    • Centralized Management: All styles are maintained in a single external file, making it straightforward to manage and update styles without touching the HTML documents.
    • Browser Cache Advantage: External stylesheets are cached by browsers, leading to faster page loading times for users who have previously visited a site using the same stylesheet.
  • Disadvantages of External CSS:
    • Additional HTTP Request: Loading an external stylesheet requires an additional HTTP request, which may marginally impact page load times, especially for smaller projects.

Difference between Inline, Internal and External CSS.

Note: There is a priority rule among inline, internal, and external CSS. This rule dictates that styles applied inline within HTML elements take precedence over styles defined internally in the document (via `<style>` tags) and externally linked CSS files. In other words, if a tag has styles applied inline, those styles cannot be overridden by internal or external stylesheets. Similarly, if styles are defined internally, they will not be affected by external CSS rules.

CSS Selectors

ID and Class Concept

  • ID is unique, indicated by "#" symbol, meaning an ID with a particular name should be only one in the entire HTML page.
  • Class can be applied to multiple elements, denoted by "." symbol.
  • Purpose of ID:
    • We use ID if a component is unique and singular, and we want to apply styles or interact with that specific component through JavaScript or CSS.
    • IDs are commonly used for anchoring, linking, and for JavaScript interactions where a single, unique element reference is required.
  • Purpose of class:
    • Classes are used when multiple elements share common styles or functionality.
    • They allow for the efficient application of styles across different elements without duplicating code.
    • Classes are versatile and can be reused across different elements to maintain consistent styling or behavior.
    • They are particularly useful for applying styles to groups of elements, such as navigation menus, buttons, or sections.

CSS Element Selector

  • The CSS element selector is used to select and apply styles to all instances of a particular HTML element on a webpage. It targets all elements of the specified type.
  • When using the element selector, the defined styles will be applied universally to all HTML elements matching the selected tag.
  • This selector is useful for applying consistent styles across multiple elements of the same type throughout the webpage.

Example:

                    
<!DOCTYPE html> 
<html> 
    <head> 
        <title>Document</title>
        <style> 
            /* Applying styles to all <p> elements */
            p {
                font-size: 16px;
                color: #333;
                line-height: 1.5;
                /* Additional styles can be added here */
            }
        </style>
    </head>
    <body>
        <p>This is a paragraph tag and styles are being applied to this using element selector</p>
    </body>
</html>
                    
                

CSS ID Selector

  • The CSS ID selector is used to select and apply styles to a specific HTML element with a unique identifier. It targets only one element with the specified ID.
  • When using the ID selector, the defined styles will be applied exclusively to the HTML element matching the selected ID.
  • This selector is ideal for styling or interacting with a singular, unique component on a webpage.

Example:

        
<!DOCTYPE html> 
<html> 
    <head> 
        <title>Document</title>
        <style> 
            /* Applying styles to the element with ID "unique-id" */
            #unique-id {
                font-weight: bold;
                color: #ff0000;
                /* Additional styles can be added here */
            }
        </style>
    </head>
    <body>
        <div id="unique-id">This is a div with a unique ID and styles are being applied using the ID selector</div>
    </body>
</html>
        
    

CSS Class Selector

  • The CSS class selector is used to select and apply styles to multiple HTML elements that share a common class attribute. It targets all elements with the specified class.
  • When using the class selector, the defined styles will be applied to all HTML elements that have the specified class.
  • This selector is useful for applying consistent styles to groups of elements across the webpage.

Example:

        
<!DOCTYPE html> 
<html> 
    <head> 
        <title>Document</title>
        <style> 
            /* Applying styles to all elements with class "example-class" */
            .example-class {
                font-style: italic;
                color: #007bff;
                /* Additional styles can be added here */
            }
        </style>
    </head>
    <body>
        <p class="example-class">This is a paragraph with the class "example-class" and styles are being applied using the class selector</p>
        <div class="example-class">This is a div with the class "example-class" and styles are being applied using the class selector</div>
    </body>
</html>
        
    

Universal Selector

  • The Universal Selector (*) is used to select and apply styles to all elements on a webpage.
  • When using the Universal Selector, the defined styles will be applied universally to all HTML elements.
  • This selector is useful for applying global styles or resetting default browser styles across the entire webpage.

Example:

        
<!DOCTYPE html> 
<html> 
    <head> 
        <title>Document</title>
        <style> 
            /* Applying global styles to all elements */
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
                /* Additional styles can be added here */
            }
        </style>
    </head>
    <body>
        <h1>This is a heading and styles are being applied using the Universal Selector</h1>
        <p>This is a paragraph and styles are being applied using the Universal Selector</p>
        <div>This is a div and styles are being applied using the Universal Selector</div>
    </body>
</html>
        
    

Group Selector

  • The Group Selector allows you to apply the same styles to multiple selectors by grouping them together.
  • When using the Group Selector, the defined styles will be applied to all elements matched by the grouped selectors.
  • This selector is useful for reducing redundancy in CSS code and applying consistent styles to multiple elements with different selectors.

Example:

        
<!DOCTYPE html> 
<html> 
    <head> 
        <title>Document</title>
        <style> 
            /* Applying the same styles to multiple selectors */
            h1, h2, h3 {
                font-family: Arial, sans-serif;
                color: #333;
                /* Additional styles can be added here */
            }
        </style>
    </head>
    <body>
        <h1>This is a heading and styles are being applied using the Group Selector</h1>
        <h2>This is another heading and styles are being applied using the Group Selector</h2>
        <h3>This is yet another heading and styles are being applied using the Group Selector</h3>
    </body>
</html>
        
    

CSS Box Model

The CSS Box Model is a fundamental concept in web design that describes how elements are structured and spaced within a webpage. It consists of several key components that define the dimensions and layout of an element.

Key components of the CSS Box Model:

Manipulating Box Model Styles Using CSS

The box model in CSS allows developers to control the dimensions and spacing of elements on a webpage. This is achieved through properties like padding, margin, and border.

    
div {
    padding-left: 10px;
    padding-right: 20px;
    padding-top: 30px;
    padding-bottom: 40px;

    margin-left: 10px;
    margin-right: 20px;
    margin-top: 30px;
    margin-bottom: 40px;

    border: 2px solid red;
}

/* We can also use the following shortcut syntax */
p {
    padding: 30px 20px 40px 10px; /* top, right, bottom, left */
    margin: 30px 20px 40px 10px; /* top, right, bottom, left */
}
    

In the CSS code above:

Pseudo Classes

Syntax:

                    
selector:pseudo-class {
    property: value;
}
                    
                

Examples of pseudo-classes:

:hover

  • We use it when we want to apply styles to an element when the mouse pointer is over it.
  • Example:
    
button:hover {
    background-color: yellow;
    color: black;
}
    

:active

  • We use it when we want to apply styles to an element while it is being activated by the user, typically when clicking on it.
  • Example:
    
button:active {
    background-color: green;
    color: white;
}
    

:link

  • We use it when we want to apply styles to unvisited links.
  • Example:
    
a:link {
    color: blue;
}
    

:visited

  • We use it when we want to apply styles to visited links.
  • Example:
                    
a:visited {
    color: purple;
}
                    
                

:last-child

  • We use it when we want to apply styles to the last child of a parent element.
  • Example:
                    
ul li:last-child {
    font-weight: bold;
}