Monday 19 June 2023

An Examination of the CSS Display Property (Part 2/3)

Block elements are responsible for much of the layout in HTML. While inline elements tend to focus more on content, block elements are usually the placeholders that house that content.

The common div tag is a ubiquitous example. So are paragraph and header tags. In fact, many of the tags introduced in HTML5 are block-level elements - footer, aside, article, section and so on. Basically, tags that, before HTML5, might have been represented as div tags.

display: block

One feature of a block element is that they will always start on a new row.

Let's try this with a paragraph.
Here is a <p style="outline:1px solid red;">paragraph tag</p> for illustration.


Here, we see that the content of the tag is on its own line! And it has a top and bottom margin, to boot.
Here is a

paragraph tag

for illustration.


Another feature of block-level elements is that if width is not specified, they take up the entire width of their parents by default.
Here is a <div style="outline:1px solid red;">div tag with no width specified</div> for illustration.
<br />
Here is a <div style="outline:1px solid red;width:50%">div tag with 50% width specified</div> for illustration.


The div tags still take up their own row, but only the first one, with no width specified, takes up the entire row. Unlike the paragraph example above, it has no padding by default.
Here is a
div tag with no width specified
for illustration.
Here is a
div tag with 50% width specified
for illustration.


Now how about height and padding? Let's see...
Here is a div tag <div style="outline:1px solid red;height:50px;width:100px;padding:5px">with a little padding</div> for illustration.
<br />
Here is a div tag <div style="outline:1px solid red;height:50px;width:100px;padding:20px">with more padding</div> for illustration.


The padding works vertically and horizontally, and both width and height are honored!
Here is a div tag
with a little padding
for illustration.
Here is a div tag
with more padding
for illustration.


And of course, since there are widths specified, the float property will work!
<div style="outline:1px solid red;height:50px;width:100px;padding:5px;float:left">Floated left with a little padding.</div>
<div style="outline:1px solid red;height:50px;width:100px;padding:20px;float:right">Floated right with more padding</div>


Floated left with a little padding.
Floated right with more padding



Next

Using inline-block.

No comments:

Post a Comment