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
Why does <span> break outside <div> when margin and padding is applied?
提问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
回答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。