11
votes

In the code below, I am trying to get the h1 element to have a top-margin. When I set the position to inline in the css, the margin-top doesn't show up. But when I change it to inline-block, it does. I am wondering if somebody can explain why this is the case. Thanks.

EDIT: Here's the code in jsfiddle: http://jsfiddle.net/pjPdE/

Here's my 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>

And here's the CSS

body {
    background-image:url('sharks.jpg');
    }

h1 {
    background-color:#1C0245;
    display:inline;
    padding: 6.5px 7.6px;
    margin-left:100px;
    margin-top:25px;
}
3

3 Answers

17
votes

Section 9.2.4 of the CSS2 specification states:

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.

Further on in the CSS2 specification (section 9.4.2) we get told that inline elements only respect horizontal margins (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.

The difference between inline and inline-block is that inline elements are treated as inline whereas inline-block elements are effectively treated as blocks (which are visually inline with each other).

Block-level elements respect both horizontal and vertical margins whereas inline-level elements only respect horizontal margins.

5
votes

The <h1> tag is by default a block element which allows margins. Using display: inline turns it into an inline element such as a span tag which does not allow margins.

Using display: inline-block allows you to use both features of both elements.

Displays an element as an inline-level block container. The inside of this block is formatted as block-level box, and the element itself is formatted as an inline-level box

Reference : w3schools

2
votes

Only block level elements can have margins. giving it 'display: inline; forces it (unsurprisingly) to become an inline element, thus losing it's margin.

Try using inline-block if you want to keep it inline with other content and take advantage of margins . . .