在下面的代码中,我试图让 h1 元素有一个上边距。当我在 css 中将位置设置为内联时,margin-top 没有显示。但是当我将它更改为内联 block 时,它确实如此。我想知道是否有人可以解释为什么会这样。谢谢。
编辑:这是 jsfiddle 中的代码:http://jsfiddle.net/pjPdE/
这是我的 HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="MyFirstWebsite.css">
<title>
Max Pleaner's First Website
</title>
</head>
<body>
<h1>Welcome to my site.</h1>
</body>
</html>
这是 CSS
body {
background-image:url('sharks.jpg');
}
h1 {
background-color:#1C0245;
display:inline;
padding: 6.5px 7.6px;
margin-left:100px;
margin-top:25px;
}
最佳答案
Section 9.2.4 CSS2 规范声明:
inline-block
This value causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.inline
This value causes an element to generate one or more inline boxes.
在 CSS2 规范 ( section 9.4.2 ) 中,我们被告知内联元素只考虑水平边距 ( proof ):
In an inline formatting context, boxes are laid out horizontally, one after the other, beginning at the top of a containing block. Horizontal margins, borders, and padding are respected between these boxes.
inline
和 inline-block
的区别在于 inline
元素被视为内联,而 inline-block
> 元素被有效地视为 block (它们在视觉上相互内联)。
block 级元素同时考虑水平和垂直边距,而内联级元素只考虑水平边距。
关于html - 为什么 margin-top 与 inline-block 一起工作而不与 inline 一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19153573/