Loading course content...
Loading course content...
Let's consider the following example:
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit.
<a href="/"
>Fuga blanditiis delectus voluptatum molestias accusantium id repudiandae
exercitationem!</a
>
Labore ipsum blanditiis vero, doloremque, nisi vel molestiae ea odio tempore
recusandae dicta?
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Illum itaque eaque
esse inventore incidunt delectus quia? Eos nam fuga sint obcaecati magnam.
Fuga voluptatem doloremque quisquam eligendi libero. Deleniti, rerum.
</p>
Notice that the <p> element always starts on a new line and takes up as much horizontal space as possible.
But the <a> element only takes up as much space as necessary, and does not start on a new line.
This is the difference between the block elements and inline elements.
Block elements automatically take up all the horizontal space available, and you can customize their width and height.
Inline elements only take as much space as necessary, and defining width and height has no effects.
However, you sometimes need to be more flexible in practice.
For example, when building a navigation bar, and you have a list of links here:
<ul>
<li><a href="#">Link1</a></li>
<li><a href="#">Link2</a></li>
<li><a href="#">Link3</a></li>
<li><a href="#">Link4</a></li>
</ul>By default, <li> is a block element occupying the entire 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:
li {
display: inline;
}And now, the <li> will be displayed as an inline element.
You can also make an inline element behave like a block element in a similar way.
<div><span>#1</span><span>#2</span></div>span {
border: 2px solid black;
display: block;
}If you need an inline element but you want to be able to customize its width and height, use inline-block:
span {
border: 2px solid black;
display: inline-block;
width: 100px;
height: 50px;
}<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="/styles.css"> </head> <body> <ul> <li><a href="#">Link1</a></li> <li><a href="#">Link2</a></li> <li><a href="#">Link3</a></li> <li><a href="#">Link4</a></li> </ul> </body> </html>