<img>标签之间的空格

13

如果我使用以下代码(两个标签之间有空格):

<img src="....." style="border:0px;margin:0px" />
<img src="....." style="border:0px;margin:0px" />

图片之间有4个像素的间距。如果我使用以下代码:

<img src="....." style="border:0px;margin:0px" /><img src="...." style="border:0px;margin:0px" />

所有浏览器上的图片之间的空隙都消失了!

为什么?????


2
任何数量的空格(也称为空格)都会呈现为一个空格字符,其默认宽度可能为4个像素。换行符也被呈现为空格。 - Shadow The Spring Wizard
7个回答

13

这是因为对于内联元素,空白符是至关重要的。如果您想让它们排成一行,可以始终将图像浮动。

编辑: 根据要求,这里有一个简单的示例:

/* This is used to "clear" the floated elements */
.images { overflow: hidden; width: 100% }

/* float the elements so that white space does not matter */
.images img { float: left; }
<div class="images">
    <img src="http://dummyimage.com/150x100/000/fff&text=first+image" alt="first image" />
    <img src="http://dummyimage.com/150x100/6aa8de/fff&text=second+image" alt="second image" />
    <img src="http://dummyimage.com/150x100/ff6500/fff&text=third+image" alt="third image" />
</div>


1
浮点数可以避免这个问题,但是浮点数也有很多其他的特点。如果他确实希望图片在行内显示,那么浮点数无法解决这个问题。 - Spudley
很多怪癖?浮动元素在所有浏览器中都是非常标准的。 - wsanville

8
<img src="http://www.nataliedee.com/111908/whatever-dude-whatever.jpg" style="border:0px;margin:0px;float:left;width:200px;" />
<img src="http://www.nataliedee.com/111908/whatever-dude-whatever.jpg" style="border:0px;margin:0px;clear:both;width:200px;" />

http://jsfiddle.net/JNWc7/


2
问题是为什么会发生这种情况(带有大量的问号)。这并没有回答那个问题。 - glennsl

6
出于与此段落中字母a和b之间的空格相同的原因:
<p>a
b</p>

任何 HTML 中的空格都会被视为一个空格(并折叠成一个空格)。

5
这是因为HTML将换行符视为空白字符,而空白字符会被显示出来。

3
有很多好的答案可以回答这个问题,但我认为这可能对未来需要它的任何人都有用。 <img> 元素像文本一样流动,但也像块元素一样具有宽度和高度。在 CSS 中,您可以将元素设置为 display:inline-block 以使其复制图像的行为,因此将 <img> 视为 inline-block (浏览器技术上使用 display: inline,但它们正在像 inline-block 元素一样特殊处理图像)。
因此,如果您在它们之间添加一个空格、制表符或换行符,将出现间隙。
根据情况,您可以使用以下方法之一消除间隙:
  • Add a negative margin-left
  • Use float
  • Remove the whitespace between the elements, which can be done:

    1- Put theme in one line

    <img src="..."><img src="...">
    

    2- Removing the space

    <img src="..."><
    img src="...">
    

    3- Use HTML comments

    <img src="..."><!--
    --><img src="...">
    

    4- Skip the closing tag (in case there it is like li). (HTML5 only)

    <ul>
       <li>First
       <li>Second
    </ul>
    

    5- font-size: 0 on parent element


1
“font-size: 0” 是我在 Stack Overflow 上看到的最聪明的想法之一。而且比浮动效果副作用要少得多! - Thomas

1
如果您在包含图片的 div 中没有任何文本,则 font-size:0; 也可以解决此问题。

1

这是因为你的换行符被渲染成了空格。

为避免此问题,请确保标签之间没有空格。 以下是我通常做的:

<img src="....." style="border:0px;margin:0px"
 /><img src="....." style="border:0px;margin:0px" />

没错,它看起来很丑。但这是处理它的最佳方式。

关于其他答案的说明:浮动具有各种不同的效果,您可能不想要(最重要的是,它们会浮动到您的其他内容旁边)。如果您只想要内联图像,那么这就是您的解决方案。


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