简体   繁体   English

为什么包含在内联块级元素内的块级元素显示为内联?

[英]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/ 我创建了一个小提琴来展示这个问题: 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. <a>标签设置为display:inline-block<span>display:block ,当<span>未被<a>标签包围时,它会跨越页面的整个宽度,正如我所期望的那样块级元素应该。 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. 当如上所示用a标签括起来时,即使在开发工具中检查它仍然将其显示为块元素,它看起来就像显示为内联。 Why does this happen and why doesn't the <span> span the entire width of the <a> element? 为什么会发生这种情况,为什么<span>不会<span> <a>元素的整个宽度?

There's no place for your span element to take the entire width of the page. 您的span元素无法占据页面的整个宽度。 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. 所以你的块级元素确实占用了父宽度的100%。

Since there is no width defined for the parent inline-block , it takes whatever space it gets inside the inline-block element. 由于没有为父inline-block定义width ,因此它占用了inline-block元素中的任何空间。 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. 为了演示这一点,如果我为你的inline-block元素指定一些width ,则span将获取父元素的所有可用宽度。

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. 在这里,当您为父内联块元素指定width ,您的span将获取它获得的所有宽度。


Another example, added box-sizing to count the padding inside the element, and appended width: 100%; 另一个例子,添加了box-sizing来计算元素内部的padding ,并附加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 演示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. 请注意,在内联块元素内呈现级元素不会强制父元素占用文档上的所有可用水平空间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM