p和div之间的差异作为块元素

时间:2017-02-09 10:49:28

标签: html css

我有两个示例程序如下:

计划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>

计划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>

我有一些澄清:

a)虽然<p><div>是块元素,但为什么<div>表现出完全的内联块类型是可接受的显示区别。

但为什么<p>元素的行为在这里有所不同?

2 个答案:

答案 0 :(得分:4)

<p>元素具有默认边距。此外,非浮动<p>元素的上边距collapses with the <body> element,而浮动<p>元素的边距不是。这导致两个段落未对齐:浮动<p>的外(边缘)边缘与<body>的内边缘(边缘)对齐,而非两者的内边缘浮动<p><body>相互对齐。

<div>没有此类默认边距,因此两个<div>元素对齐就好了。

其他人谈论两个元素之间的语义差异 - 虽然这不是直接相关的,因为这是CSS而不是HTML的问题,它确实解释了为什么 <p>来首先使用默认边距:因为段落是由空格在视觉上分隔的文本的单独运行。

答案 1 :(得分:1)

所有浏览器都具有p等元素的默认CSS值,例如margin,这使得两个版本的渲染方式不同。

这就是为什么通常使用NormalizeReboot等CSS文件将所有浏览器重置为相同值并从那里构建。