CSS Tutorial - Lesson 4 - The display property. Difference between div and span.
In previous lessons, we connected CSS via a file and wrote a bit of CSS code to see how it works. In this lesson, we’ll explore an important property: display. The display property determines how an HTML element is rendered in the document—whether it will be displayed inline like text or as a block that has its own width and height. Let's start with the basics: how tags are displayed by default. For example, a <div> is displayed as a block, while a <span> is inline like text. Let's begin with how text is displayed. We’ll create a test string and wrap it in a span tag.
display: inline
The span
tag is displayed inline, as text should be (except for vertical writing systems like Japanese). A span tag doesn’t have height or width; you can’t assign these properties with display: inline. That’s because text is measured using other characteristics: font size, font family, color, letter spacing, line height, word spacing, and text indent. So if you want to define dimensions or spacing, use the next display value.
display: block
The value block
is the default for the div
tag. It allows you to define width, height, and margins. This means we can create sections on a page and insert text, images, or even other blocks. You can even assign display: block
to a span
tag, and it will behave like a block (ideally used with a class, e.g., <span class="block">text</span>).
Another feature of block elements is that they expand to the full available width by default (width: 100%). But you can’t set height to 100% unless specific conditions are met. The block will be only as tall as its content. You can specify height in pixels (like 800px), but full-height layout is trickier. We’ll cover that in future articles.
display: inline-block
Sometimes we want images to behave like blocks—have width, height, and margins—but still appear inline, side by side. For that, we can use inline-block. This value combines the characteristics of both inline and block elements. You can assign display: inline-block
to regular block elements too.
display: table
The table
value is the default for tables. Unlike blocks, tables can stretch to 100% height. But we still prefer block-based layout over table-based layout, because tables should only be used for tabular data—not for layout purposes.
display: list-item
With list-item
(used by default for the <li> tag), a bullet or marker is automatically added (a black circle by default).
display: none
If you assign this value to a class, tag, or ID, the element will be hidden on the page! Be careful with this—it’s easy to hide something important and later wonder why it’s missing. However, if a client asks you to remove something (like an RSS icon), you can do this:
.rss {
display: none;
}
Of course, it’s better to remove the element from the template entirely. But if it’s already being rendered, hiding it with CSS can be a quick fix.