# span标签之间的空白间距问题
# 前言
平时在实现ui的设计稿的时候会遇见一些小问题, 比如莫名其妙的间距, 明明没有加margin和padding, 但是就是会出现间距, 这就是两个span标签的间距问题.我们今天就这个问题进行分析.
# 现象描述
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<span>hello</span>
<span>world</span>
<span>helloworld</span>
</body>
</html>
我们看这样一段代码, 他展示出来的效果是这样的
可以看到, 我们的span上没有应用任何样式, 但是仍然出现了间距. 又或者是下面这段代码;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.inline-block {
display: inline-block;
width: 100px;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<div class="inline-block"></div>
<div class="inline-block"></div>
</body>
</html>
他的效果是这样的:
我们也可以很明显的看到, 两个div直接出现了间隙.那么, 这个间隙到底是怎么出现的呢?
# 原因
导致这个现象出现的原因很简单, 我们知道多个空格或者回车浏览器都会解析成空格, 其实, 我们span与span之间敲的回车, 就被解析成了空格.所以, 那一点间隙, 其实就是这个空格, 如果不理解, 看下面这段代码就能理解了.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<span>hello world</span>
<br>
<span>hello
world
</span>
<br>
<span>hello</span>
<span>world</span>
</body>
</html>
他的效果是这样的;
怎么样, 是不是一模一样, 这下你能理解为什么我们没有加margin和padding, 没有添加任何样式, 他们之间也存在间距了吧?
# 解决方案
既然知道了原因, 那这个问题就很好解决了.
代码中不要写空格: 既然这个问题是空格导致的, 那我们不要空格或者回车, 这个问题就解决了
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <span>hello</span><span>world</span> <br> <span>hello</span ><span>world</span> </body> </html>
像上面这种写法, 展现出来的效果就是:
这样两个单词之间的间距就没有啦, 不过这种写法会导致我们的代码不整洁, 对于有强迫症的小伙伴来说是接受不了的, 我们可以用其他的方法来解决这个问题.
通过css去消除间距 既然它出现了间距, 那我们啥也不管, 把它弄掉就行了, 我们可以用样式把间距去掉, 比如用margin/word-spacing/letter-spacing等:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body=> <span>hello</span> <span style="margin-left: -5px;">world</span> <div style="word-spacing: -40px;"> <span>hello</span> <span>world</span> </div> </body> </html>
效果是下面这样的:
可以看到这样也能消除间距, 但是如果使用margin, 不能保证在任何情况下两个单词都恰好没有间距.而自己在chrome中测试发现, word-spacing的负值足够大的情况下, 不会将两个单词重叠, 只会紧紧贴住.所以设置一个负值较大的word-spacing看起来是一个比较好的方法, 但是不清楚在其他浏览器中是否和chrome保持一致.
通过设置font-size消除间距 这种方法是我平时喜欢用的, 既然空格占了位置, 那么我们把font-size设置为0, 空格就不会占位置了, 同时再单独设置子元素的字体大小, 就能干掉这个间隙了.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div style="font-size: 0;"> <span style="font-size: 20px;">hello</span> <span style="font-size: 20px">world</span> </div> </body> </html>
他的效果是这样的:
# 结语
总的来说, 肯定有很多方法可以去掉这个空隙, 但是最普遍的集中方法就是这几种了.同时, 只要我们知道了这个空隙为何而来, 我们就能对症下药, 找到解决问题的办法.