Div Span - HTML Tutorial
As we’ve seen, using CSS is straightforward: you provide a selector (for example, “select all p elements”), define a rule (like “make their text red”), and the browser applies it. While CSS selectors and rules can get quite sophisticated, this is the core idea.
Next, let’s look at two generic HTML elements: div and span. These elements are versatile containers that let you target arbitrary sections of HTML for styling.
The span Element
The span element is a generic inline container. Here’s an example:
span<p>
Towards thee I roll, thou all-destroying but unconquering whale;
<span>to the last I grapple with thee; from hell's heart I stab
at thee; for hate's sake I spit my last breath at thee.</span>
Sink all coffins and all hearses to one common pool!
</p>
By default, the span element does not change the appearance of content. It acts as a placeholder, marking the start and end of a section for potential styling.
We can add a class and apply CSS to make the text inside the span stand out:
span<html>
<head>
<title>Moby-Dick</title>
<style>
span.highlight { color: #ff0000; }
</style>
</head>
<body>
<p>
Towards thee I roll, thou all-destroying but unconquering whale;
<span class="highlight">to the last I grapple with thee;
from hell's heart I stab at thee.</span>
Sink all coffins and all hearses to one common pool!
</p>
</body>
</html>
Now, the text inside the <span class="highlight"> is styled in red, demonstrating how span can target specific inline content.
Tip
Use span sparingly. Prefer semantic elements like em, strong, code, or other logical styles when possible, as they convey meaning and improve accessibility.
The div Element
The div element is a generic block-level container. It’s used to style larger sections of HTML, like multiple paragraphs. Every div creates a “box” around its content that CSS can target.
div<html>
<head>
<title>Product Brochure</title>
<style>
div.important { color: #ff0000; }
</style>
</head>
<body>
<p>Congratulations on the purchase of your sword! Follow these safety tips.</p>
<div class="important">
<p><em>Never</em> hold your sword by the pointy end.</p>
<p><em>Always</em> point it away from yourself and others.</p>
</div>
<p>And remember, our money-back guarantee applies if you’re not satisfied.</p>
</body>
</html>
The div applies styles to all content inside it (here, the two paragraphs). Unlike inline elements, div defines a block, but it doesn’t automatically add extra spacing between paragraphs. Inserting a div inside a paragraph, however, creates a new block.
