-1

I have two sample programs as follows:

Program A:

<!DOCTYPE html>
<html>
<head>
<style>


</style>
</head>
<body>

<p style="float:left">This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.</p>
<p>This is also some text. This is also some text. This is also some text. This is also some text. This is also some text. This is also some text.</p>

Program B:

<!DOCTYPE html>
<html>
<head>
<style>


</style>
</head>
<body>

<div style="float:left">This is some text. This is some text. This is some text. This is some text. This is some text. This is some text.</div>
<div>This is also some text. This is also some text. This is also some text. This is also some text. This is also some text. This is also some text.</div>

I have a few clarifications :

a) Although <p> and <div> are block elements , why is there a difference in display where <div> is behaving a perfect inline-block type which is acceptable .

But why is the behaviour of <p> element different here ?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user1400915
  • 1,933
  • 6
  • 29
  • 55
  • 1
    **The

    tag defines a paragraph.** and **The

    tag defines a division or a section in an HTML document.**
    – Weedoze Feb 09 '17 at 10:50
  • 1
    Inspect the elements' default CSS in your browser's element inspector. They have different default styles, most notably `p` has a margin. Because they're different elements, used for different purposes. – deceze Feb 09 '17 at 10:52

2 Answers2

4

The <p> element has default margins. Furthermore, the non-floating <p> element's top margin collapses with the <body> element, while the floating <p> element's margin does not. This is what results in the two paragraphs being misaligned: the floating <p>'s outer (margin) edge is aligned with the inner (border) edge of <body>, while the inner edges of both the non-floating <p> and <body> are aligned with each other.

<div> has no such default margins, so the two <div> elements align just fine.

The others talk about semantic differences between the two elements — while that isn't directly pertinent here since this is a matter of CSS and not HTML, it does explain why <p> comes with default margins in the first place: because paragraphs are individual runs of text that are visually separated by whitespace.

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
1

All browsers have default CSS values for elements like p, such as margin which makes your two versions render differently.

That's why it is common to use CSS files like Normalize or Reboot to reset all browsers to the same value and build from there.

MrD
  • 819
  • 6
  • 6