Html 当应用边距和填充时,为什么 <span> 会在 <div> 之外中断?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10666032/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:31:58  来源:igfitidea点击:

Why does <span> break outside <div> when margin and padding is applied?

htmlcss

提问by user1405195

I know this is very basic CSS. How do I keep the span contained within the div? At the moment, the span extends outside the top and bottom of the div.

我知道这是非常基本的 CSS。如何保持跨度包含在 div 中?目前,跨度延伸到 div 的顶部和底部之外。

div {
  width: 200px;
  margin: 10px;
  background-color: #ff0;
}
span {
  margin: 5px;
  padding: 5px;
  background-color: #fc0;
}
<body>
  <div>
    <span>span</span>
  </div>
</body>

回答by gmeben

To answer your question, this isn't just an issue with paddingor margin, but also with width, display, and the box model.

要回答你的问题,这不仅是一个问题与padding或者margin,也可与widthdisplay盒模型

jsFiddle

js小提琴

span {
    display: inline-block;
}

This will honor any padding, margins, or widths you apply to the span.

这将尊重您应用于跨度的任何填充、边距或宽度。

回答by Matthew

Inline elements will not consume vertical padding and margin space. You can make the span display: block, but without more detail I don't know if that will achieve your goal.

内联元素不会消耗垂直填充和边距空间。您可以制作 span display: block,但如果没有更多细节,我不知道这是否会实现您的目标。

回答by roger

The vertical padding, border and margin of an inline, non-replaced box (e.g. span) 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. Therefore you see an overlapping here: http://jsfiddle.net/Q9AED/

内联、非替换框(例如跨度)的垂直填充、边框和边距从内容区域的顶部和底部开始,与“行高”无关。但是在计算线框的高度时只使用“line-height”。因此,您在这里看到重叠:http: //jsfiddle.net/Q9AED/

If you want to use a straightforward solution, you can use line-height rather than display: inline-block: using line-height.

如果你想使用一个简单的解决方案,你可以使用 line-height 而不是 display: inline-block: using line-height

display: inline-block works in Safari >= 2, Opera >= 9, IE >= 8, Firefox > 3. But you can imitate an inline-block in IE < 8: display: inline; zoom: 1.

display: inline-block 适用于 Safari >= 2, Opera >= 9, IE >= 8, Firefox > 3。但是你可以在 IE < 8 中模仿 inline-block: display: inline; 缩放:1。