首页 文章

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

提问于
浏览
4

我创造了一个小提琴,只是为了证明这个问题:https://jsfiddle.net/vanillasnake21/bf0j0v5L/

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

<a> 标记设置为 display:inline-block<span>display:block ,当 <span> 未被 <a> 标记包围时,它跨越页面的整个宽度,正如我期望的块级元素应该的那样 . 当如上所示用a标签括起来时,它看起来只是'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' _ <span> 跨越 <a> 元素的整个宽度?

1 回答

  • 5

    span 元素无法占据页面的整个宽度 . 从技术上讲,您在内联块元素中呈现块级元素 . 所以你的块级元素确实占用了父宽度的100% .

    由于没有为父 inline-block 定义 width ,因此它占用 inline-block 元素内的任何空间 . 为了演示这一点,如果我将 width 分配给你的 inline-block 元素, 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

    在这里, span 获取所有宽度,因为您已将 width 分配给父内联块元素 .


    另一个例子,添加 box-sizing 来计算元素内的 padding ,并将 width: 100%; 附加到父元素 .

    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


    请注意,在内联块元素内呈现块级元素不会强制父元素占用文档上的所有可用水平空间 .

相关问题