What is the Difference between Block, Inline, and Inline-block in CSS

Recall that we introduced the block and inline elements at the beginning of this chapter, where we explored the basics of HTML.

Block elements are those that automatically take up all the horizontal space available, but you can define custom width and height. Inline elements, on the other hand, only take as much space as necessary, and defining width and height has no effect on these elements.

Inline

However, you sometimes need to be more flexible when working on real-life projects. For example, you are trying to build a navigation bar that sits on top of the page, and you have a list of links here:

html
1<ul>
2  <li><a href="#">Link1</a></li>
3  <li><a href="#">Link2</a></li>
4  <li><a href="#">Link3</a></li>
5  <li><a href="#">Link4</a></li>
6</ul>

By default, <li> is a block element occupying the horizontal line.

This would waste a lot of vertical space. To fix this issue, you can change how the <li> elements are displayed using the display property.

css
1li {
2  display: inline;
3}

And now, the <li> will be displayed as an inline element.

Open demo in new tab

Block

You can also make an inline element behave like a block element in a similar way.

html
1<div><span>#1</span><span>#2</span></div>
css
1span {
2  border: 2px solid black;
3  display: block;
4}
Open demo in new tab

Inline block

If you need an inline element but you want to be able to customize its width and height, you can use inline-block instead.

css
1span {
2  border: 2px solid black;
3  display: inline-block;
4  width: 100px;
5  height: 50px;
6}
Open demo in new tab

display vs. visibility

display can also control whether or not an element is rendered on the webpage. If you set display to none, the element will not be displayed. This can create useful features when combined with JavaScript, allowing you to toggle the element on and off.

This behavior is very similar to another CSS property called visibility. Their difference is that when visibility is set to hidden, the element is still on the webpage, just not displayed by the browser. It will take up the same space as before. When display is set to none, the element will be completely removed from the webpage.

The display property is probably the most important CSS property we are going to cover in this chapter. It not only controls the display types of individual elements, but also the layout of its children. However, this requires a deeper understanding of CSS, so we will come back to this topic later.