div内的span位置问题?

为什么我给div里的span标签写了padding:5px,span的内边距会跑到div的外面,而不是跟div的上边缘对齐?

clipboard.png

clipboard.png

clipboard.png

阅读 12.1k
2 个回答

这个问题可以从两个地方来看,一是span自己的盒模型高度,二是外层div容器的高度。

题主的疑问其实就是,为什么span的盒模型超出了作为容器的div的范围。

首先,虽然span是一个行内元素(inline),但水平与垂直方向的padding都是有效的,这将决定它的盒模型范围。background-color默认将铺满整个border-box,由此得到一个稍大一圈的蓝色背景。

然而span作为一个行内元素参与布局,是另一回事。w3c是这样解释的:

The vertical padding, border and margin of an inline, non-replaced box start at the top and bottom of the content area, and has nothing to do with the 'line-height'. But only the 'line-height' is used when calculating the height of the line box.

意思是说,垂直方向的padding等不会影响到line-height,而对于span这类行内元素来说,它的line-height才是真正决定它参与布局时所占据的高度。注意这句话最后提到了line box,行框。

作为容器的div,题主加了黑色描边,对应的是border-box的范围。这个块元素的范围是如何决定的,也有对应的解释:

The element's height is the distance from its top content edge to the first applicable of the following:

  1. the bottom edge of the last line box ...

可见,div的实际高度是由行框(line box)的高度决定的。 因此,span自己的内边距形成的盒模型,可以这样随意超出。

因为span是inline.
加一段css
span{display: inline-block}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题