Question

I am stuck trying to figure it out how exactly inline element and floated element behave when are next to each other. I have following code in which inline element comes before the floated one and the second situation when inline element comes after the floated one and in both situation.

html code is the same in both examples so I am gonna put it just here:

<body>
    <p class="first">first paragraph</p>
    <p class="second">second pargraph</p>
    <p class="clearBoth"></p>
 </body>

So here is first example in which is the inline element before the floated one, along with following css:

html{
    background:white;
}
p.clearBoth{
    clear:both;
}
body{
    width:400px;
    margin:0 auto;
    background:red;
   }
    p.first{
    display:inline;
    background:yellow;
    color:black;   
    }
   p.second{
   float:left;         
   background:black;
   color:white;
}

and here is the link what this code does

Here is second example where the floated element is first element, along with the following css code:

html{
    background:white;
}
p.clearBoth{
    clear:both;
}
body{
    width:400px;
    margin:0 auto;
    background:red;
   }
    p.first{
    float:left;
    background:yellow;
    color:black;   
    }
   p.second{
   display:inline;         
   background:black;
   color:white;
}

And here is link what it does

In both cases I've noticed that the float element will be first to the left no matter which one is first in html document, but I find this align very strangeto happen since I would normally expect both to be in same line.

Was it helpful?

Solution

That's because web browsers apply a margin property to the top and bottom of the <p> element.

For instance, Google chrome applies the following:

-webkit-margin-before: 1em;
-webkit-margin-after: 1em;

You need to reset the default user agent style sheet by using CSS Reset

As a tiny fix, just for the demo:

* { margin: 0; padding: 0; }
/* Or just:
p { margin: 0; }
*/

UPDATED DEMO #1

UPDATED DEMO #2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top