如果我有 display: inline,为什么我的背景颜色不显示?
<html>
<body>
<div style="display: inline; background-color: #555;">
<h3>test</h3>
</div>
</body>
</html>
这是我的代码。我想知道为什么我的背景颜色没有显示。如果我将 css 显示从内联更改为块,那么它就会显示出来。如果内联显示,为什么不显示? 我正在尝试了解问题的原因,而不是寻找解决方案。
<html>
<body>
<div style="display: inline; background-color: #555;">
<h3>test</h3>
</div>
</body>
</html>
Here is my code. I am wondering why my background color isn't showing. If I change css display from inline to block, then it show up. Why is it not showing up if display is inline? I am trying to understand the reason of the problem other than looking for a solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果 div 是内联的,则不会占用空间。如果您想要一个显示为子元素高度的内联元素,请使用
display: inline-block;
。至于好的讨论,我相信 QuirksMode 的观点比我自己的观点更好。要点是内联元素不会将其他元素推开。
The div doesn't take up space if it's inline. if you want an inline element that shows as the children's height, then use
display: inline-block;
.As for a good discussion, I'd trust QuirksMode's take better than my own. The gist is that an
inline
element doesn't push other elements out of the way.问题是您在
内联元素
内部有一个H3
,一个阻塞元素
。您可以通过以下方式查看发生了什么:
或使 H3 内联:
The issue is you have an
H3
, ablocking element
, inside of theinline element
.You can see what's happening with:
or make H3 inline:
div
默认是一个块元素。将块元素的显示模型更改为内联并不是一个好的做法。标题也是块元素。将块元素嵌套到内联元素中不是有效的 html。如果您想要类似突出显示的效果(仅为文本而不是整个元素框提供背景颜色),您需要使用像span
这样的内联元素。div
is a block element by default. Changing display model of a block element to inline is not a good practice. headings are block elements too. Nesting a block element into a inline element is not valid html. If you want a highlighting like effect (giving background color just to text not whole element box) you need to use an inline element like anspan
.简单的解决方案,在某些情况下最好是向包含标题的内联 div 添加一些填充
simple solution, best in some cases is to add some padding to the inline div containing your heading
CSS2.1 的最新修订版有这样的说法关于此事:
也就是说,从布局的角度来看,内联div和h3组合形成了一个内联框、一个块框和另一个内联框。只有两个内联框采用格式(即背景颜色),而块框不形成 div 定义的内联框的任何部分,因此采用其默认背景颜色设置(透明,通过背景显示)其包含块框的颜色)。
The latest revision of CSS2.1 has this to say on the matter:
In other words, from a layout point of view, the inlined div and h3 combination forms an inline box, a block box and another inline box. Only the two inline boxes take the formatting (i.e. the background-color) and the block box does not form any part of the inline box defined by the div and so takes its default background-color setting (which is transparent, showing through the background color of its containing block box).
如果您尝试创建荧光笔效果,请改用以下内容:
If you are trying to create a highlighter effect use the below instead: