Tim Akgayev
Tim Akgayev

Reputation: 309

Why is block level element contained inside inline-block level element displayed as inline?

I created a fiddle just to demonstrate the question: https://jsfiddle.net/vanillasnake21/bf0j0v5L/

<a>
  <span> close </span>
</a>

The <a> tag is set to display:inline-block and the <span> is display:block, when the <span> is not enclosed by the <a> tag it spans the entire width of the page as I would expect a block level element should. When enclosed with the a tag as shown above it just looks like it's being displayed as inline even though examining it in dev tools still shows it as a block element. Why does this happen and why doesn't the <span> span the entire width of the <a> element?

Upvotes: 5

Views: 179

Answers (1)

Mr. Alien
Mr. Alien

Reputation: 157314

There's no place for your span element to take the entire width of the page. Technically, you are rendering a block level element inside an inline block element. So your block level element does take 100% of the parent width.

Since there is no width defined for the parent inline-block, it takes whatever space it gets inside the inline-block element. To demonstrate this, if I assign some width to the inline-block element of yours, the span will take all the available width of the parent element.

a {
  display: inline-block;
  padding: 1em 7em;
  width: 400px; /* define some width here to the parent */
  background-color: green;
}

span {
  background-color: red;
  display: block;
}
a{
  display: inline-block;
  padding: 1em 7em;
  width: 400px;
  background-color: green;
}
<a>
  <span> close </span>
</a>

Demo

Here, your span takes all the width it gets as you have assigned a width to your parent inline-block element.


Another example, added box-sizing to count the padding inside the element, and appended width: 100%; to the parent element.

span {
  background-color: red;
  display: block;
}
a{
  display: inline-block;
  box-sizing: border-box;
  padding: 1em 7em;
  width: 100%;
  background-color: green;
}
<a>
  <span> close </span>
</a>

Demo 2


Note that rendering a block level element inside an inline block element will not force the parent element to take all the available horizontal space on the document.

Upvotes: 6

Related Questions