Premium HTML Course

15. HTML Div and Span

In HTML, <div> and <span> are two very commonly used elements that help with grouping and structuring content. While both elements are used to group content, they serve different purposes and have distinct characteristics.

The <div> Element

The <div> element is a block-level element used to group larger sections of content. It is often used to create containers for elements like text, images, or other HTML tags that need to be styled or grouped together.

Example: Using the <div> Tag


<div>
    <h1>This is a header inside a div</h1>
    <p>This is a paragraph inside a div</p>
</div>
        

The <div> element creates a container for the content inside, and you can apply styles or JavaScript interactions to the <div> as a whole.

The <span> Element

The <span> element is an inline element, typically used to group small sections of text or inline elements that need styling or other behaviors.

Example: Using the <span> Tag


<p>This is a <span style="color: red;">red</span> word in a paragraph.</p>
        

The <span> tag is useful when you need to apply styles to a small portion of text or inline elements within a larger block.

Differences Between <div> and <span>

Here are the main differences between the <div> and <span> elements:

Example of Layout with <div> and <span>

Below is an example demonstrating both <div> and <span> used together to create a basic layout:


<div style="background-color: lightblue; padding: 10px;">
    <h2>Welcome to Our Site</h2>
    <p>We offer the best <span style="color: red;">HTML courses</span> for learners around the world.</p>
</div>
        

In this example, the <div> element creates a container with a background color, while the <span> element is used to highlight the word "HTML courses" in red within the paragraph.

When to Use <div> and <span>

Conclusion

The <div> and <span> elements are versatile and powerful tools in HTML. Understanding when and how to use them will help you organize and style your content more effectively. In the next lesson, we will explore HTML iframes and how to embed external content into your webpage.