Block-Level and Inline Elements

Before going into the specifics of individual HTML tags, it helps to understand the difference between block-level elements and inline elements.

Block-Level Elements

Block-level elements can contain inline elements and other block-level elements. Here is an example using div and p block-level elements and a span inline element.

<div id="div1">
<p id="p1>Some <span>text inside a span.</span></p>
<div id="div2">
<p id="p2">Some more text with no span.</p>
</div>
</div>

And here is what that would look like if we add a little colour, borders and some padding.

Some text inside a span.

Some more text.

 

Usually a block-level element will be displayed on a new line. So taking the humble div as an example again.

<div><p>Div 1</p></div>
<div><p>Div 2</p></div>
<div><p>Div 3</p></div>

Would look something like this.

Div 1

Div 2

Div 3

 

If a div has no content and you do not specify a height or background or border colour, it won’t be visible when a page renders. It helps when laying out a page if you can see the divs!

Block-level elements usually expand to fill the full width of the surrounding element.

Inline Elements

Unlike block-level elements, inline elements cannot contain block-level elements. However, they can contain other inline elements. For example, the following code uses two inline elements that are nested one inside the other.

<p><span style="color:#f00;">This is red text and <strong>this is red and bold text</strong></span></p>

That looks like this.

This is red text and this is red and bold text.

Don’t worry about the style=”color:#f00;” part for now. That is known as inline CSS, which we will cover in another article.

One last bit about inline elements which I am sure you have gathered by now, is that they do not automatically start on a new line.

Nesting Elements

Whenever you nest one element inside another, there is a correct way to do it and a wrong way. It is simple really. All you need to do is pay attention to where you put your opening and closing tags. The best way is to show you.

CORRECT WAY

<div>
<p>Some normal text and <strong>some bold text.</strong></p>
</div>

WRONG WAY

<div>
<p>Some normal text and <strong>some bold text.</p></strong>
</div>

If you nest things incorrectly, the browser may have trouble displaying the page. If you get it right, then you will have no problems!

Comments

Leave a Comment

Your email address will not be published. Required fields are marked *

Loading Disqus Comments ...