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>');
});

我注意到,每当我附加时,CSS 边距/填充有点偏离.section

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

<!-- .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 相同的 CSS 间距.section

第一种格式:http: //jsfiddle.net/projeqht/NCfym/

第二种格式:http: //jsfiddle.net/projeqht/NCfym/1

所以我的问题是

为什么格式化的 HTML 标记输出的 CSS 空间与写在1行 HTML上的完全相同的标记不同?

4

3 回答 3

9

换行符在 HTML 中算作空格,因此以下代码在元素之间有空格:

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

这个也有:

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

但是这个没有空间:

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

这不是“CSS 空间”,而是老式的“HTML 空间”。:D

于 2013-07-29T14:56:26.490 回答
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>
于 2013-07-29T14:56:25.480 回答
3

这是因为 select 和 checkbox 是display: inline-block. 这使他们对空白很敏感。

inline-block 元素对空格敏感,因为 inline 元素是(否则,您必须在文本中的所有空格中编码,因为出于行为目的,文本字符被视为内联)。内联块元素的行为类似于内联元素(对空白敏感,彼此相邻而不是彼此重叠)和块元素(注意填充 CSS)。

于 2013-07-29T14:57:44.097 回答