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?
Note: An inline element cannot contain a block-level element!
An inline-block elements will respect a width . People used to¹ build column layout systems with inline-block , because it basically can do what floats could do here, except without the need to worry about clearing the float², allowing people to take advantage of wrapping which happens a bit more elegantly than float.
Block elements always start from a new line. Inline elements never start from a new line. Block elements cover space from left to right as far as it can go. Inline elements only cover the space as bounded by the tags in the HTML element.
Compared to display: inline , the major difference is that display: inline-block allows to set a width and height on the element. Also, with display: inline-block , the top and bottom margins/paddings are respected, but with display: inline they are not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With