-1

Problem:

Interested to know if there are any real-world examples in HTML/CSS when you need to use display: block on inline elements. For the reverse order, I found that display: inline could be used on <li> in a <nav> to display links vertically. I am not interested to know the difference between inline, block, and inline-block.

Current examples:

Current examples include showing how to use the display: block on <span> elements, and so forth. But many of these examples only illustrate the effect of display: block but not the actual use of it on a website.

Question:

For what reason and where on a website could it be relevant to use display: block to change elements from inline-level to block-level?

kexxcream
  • 5,873
  • 8
  • 43
  • 62

1 Answers1

1

Let's say you wanted to show a big button that links to a site. You use an anchor (<a>) tag because it can contain a hyperlink.

div {
  border: 1px solid black;
  padding: 20px;
}

.button {
  background: orange;
  color: white;
  padding: 10px;
  text-align: center;
}
<div>
  This button's on the same line! <a class="button" href="https://example.com">Click me!</a>
</div>

You add your button, but you've run into a problem: The button's on the same row as all the other text. It's inline!

Adding display: block not only adds a newline, it also gives you more control about the width and height of the button.

div {
  border: 1px solid black;
  padding: 20px;
}

.button {
  display: block;

  background: orange;
  color: white;
  padding: 10px;
  text-align: center;
}
<div>
  This button's aligned properly. <a class="button" href="https://example.com">Click me!</a>
</div>

If you wanted to control the button's width and height, while keeping it on the same line, you would use inline-block.

Further reading

benhatsor
  • 1,863
  • 6
  • 20
  • Interesting example, but wouldn't I just need to add a `

    ` element around all content and move the button outside the `

    ` instead of using `display: block`?

    – kexxcream May 18 '21 at 14:59
  • Correct. `display: block` is for situations where you want to keep the content in sections, without wrapping the text in much elements. (Usually for screen readers) – benhatsor May 18 '21 at 15:10