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:
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.
1li {
2 display: inline;
3}
And now, the <li>
will be displayed as an inline element.
Block
You can also make an inline element behave like a block element in a similar way.
1<div><span>#1</span><span>#2</span></div>
1span {
2 border: 2px solid black;
3 display: block;
4}
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.
1span {
2 border: 2px solid black;
3 display: inline-block;
4 width: 100px;
5 height: 50px;
6}
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.