在下面的代码中,我试图让h1元素具有顶级边距.当我将位置设置为在css中内联时,margin-top不会显示.但是,当我将其更改为内联块时,确实如此.我想知道是否有人可以解释为什么会这样.谢谢.
编辑:这是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;
- }
解决方法
CSS2规范的
Section 9.2.4规定:
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.
内联块和内联块之间的区别在于内联元素被视为内联,而内联块元素被有效地视为块(它们在视觉上彼此串联).
块级元素同时遵循水平和垂直边距,而内联级元素仅尊重水平边距.