为什么HTML标记中的空格会导致CSS样式不同?

7
我有以下的标记格式:
<!-- .section markup with line breaks and indentation (normal formatted coding) -->
<form id="form" name="form">
  <div class="section">
    <input type="checkbox" class="switch" />
    <select class="overlays" name="overlays">
        <option value="test">Test</option>
    </select>
    <input type="text" class="parameters" />
  </div>
</form>
<span id="plus">+</span>

我需要编写一些 jQuery 代码,以便根据需要像这样添加更多的 .section

$('#plus').click(function () {
  $('#form').append('<div class="section"><input type="checkbox" class="switch" /><select class="overlays" name="overlays"><option value="test">Test</option></select><input type="text" class="overlay_parameters" name_parameters" /></div>');
});

但是我注意到每当我添加 .section 时,CSS 的边距/填充有点偏差。

然后,我意识到如果我使用以下格式:

<!-- .section markup all in one line -->
<form id="form" name="form">
  <div class="section"><input type="checkbox" class="switch" /><select class="overlays" name="overlays"><option value="test">Test</option></select><input type="text" class="parameters" /></div>
</form>
<span id="plus">+</span>

现在,由标记提供的原始.section与通过JQUERY附加的.section具有相同的CSS间距。
第一种格式: http://jsfiddle.net/projeqht/NCfym/ 第二种格式: http://jsfiddle.net/projeqht/NCfym/1 我的问题是:
为什么格式化的HTML标记输出的CSS间距与完全相同的单行HTML标记不同?

1
请见此链接:http://quirksmode.org/css/text/whitespace.html - Bastian Rang
1
总是有 .clone()。[http://jsfiddle.net/7xWxx/](http://jsfiddle.net/7xWxx/)。它有它的问题,但可以消除内联HTML。 - Richard
3个回答

9

在HTML中,换行符被视为一个空格,因此以下代码元素之间有一个空格:

<input type="text">
<input type="text">

这个也有:

<input type="text"> <input type="text">

但是这个没有空格:

<input type="text"><input type="text">

这不是“CSS空格”,而是老派的“HTML空格”。 :D

真不敢相信我竟然没想到那个,太菜了!这让我在周末一直困扰!哈哈 :( 感谢大家的贡献! - projeqht
1
至少不是分号,projeqht。 ;) - FrostbiteXIII

3

HTML会去除多余的空行和空格,但仍会留下一个空格。

例如,以下代码将产生相同的效果:

http://jsfiddle.net/9ZqAr/

<form id="form" name="form">
    <div class="section">
        <input type="checkbox" class="switch" /><select class="overlays" name="overlays">
            <option value="test">Test</option>
        </select><input type="text" class="parameters" />
    </div>
</form> <span id="plus">+</span>

3

这是因为选择框和复选框的 display: inline-block。这使它们对空格敏感。

inline-block 元素对空格敏感,因为 inline 元素也是如此(否则,您将需要在文本中编码所有空格,因为行为上考虑文本字符是 inline 的)。inline-block 元素既像 inline 元素(对空格敏感,相邻而不是重叠),又像 block 元素(遵守 padding CSS)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接