Thursday 22 June 2023

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

Up next, we examine using the inline-block value for the display property. As far as I can tell, there are no HTML5 elements whose display property is, by default, inline-block. Therefore, this is something that a web developer has to explicitly define in the styling.

One of the most common usages of this is horizontal navigation bars.

display: inline-block

Using this value causes the element to have width, height and padding all definable (and by extension, the float property) while otherwise behaving exactly like an inline element.

Here is a span tag <span style="outline:1px solid red;width:100px;height:100px;padding:5px">with display property unmodified</span> for illustration.
<br />
Here is a span tag <span style="outline:1px solid red;width:100px;height:100px;padding:5px;display:inline-block">with display property inline-block</span> for illustration.


The first span tag behaves exactly as we would expect. The width specified is not long enough, so the span tag expands. But in the second tag, the span tag is an inline-block element, and the width's value is honored. Also, the height's specification works in the latter case but not the former.
Here is a span tag with display property unmodified for illustration.
Here is a span tag with display property inline-block for illustration.


We've tried turning an inline element into an inline-block element. What happens when we do that to a block element?
Here is a p tag <p style="outline:1px solid red;width:100px;height:100px;padding:5px">with display property unmodified</p> for illustration.
<br />
Here is a p tag <p style="outline:1px solid red;width:100px;height:100px;padding:5px;display:inline-block">with display property inline-block</p> for illustration.


In the first instance, the div takes on its own row. In the second example, the div has been changed to an inline-block element and now flows within the content in the same row! In both cases, height and padding reflect the values that have been input.
Here is a p tag

with display property unmodified

for illustration.
Here is a p tag

with display property inline-block

for illustration.


In a nutshell

Use inline elements for cases where you need the content to flow within the content that it appears in.

Use block elements for cases when you need the content to occupy its own row.

And when you need the content to flow and yet also want to control, the width, height, padding (and all associated properties), use inline-block for the display property.

See you again. Don be a stranger!
T___T

No comments:

Post a Comment