简体   繁体   English

如何删除内联/内联块元素之间的空间?

[英]How to remove the space between inline/inline-block elements?

There will be a 4 pixel wide space between these span elements:这些span元素之间将有 4 像素宽的空间:

 span { display: inline-block; width: 100px; background-color: palevioletred; }
 <p> <span> Foo </span> <span> Bar </span> </p>

Fiddle Demo小提琴演示

I understand that I could get rid of that space by removing the white-space between the span elements in the HTML:我知道我可以通过删除 HTML 中span元素之间的空白来摆脱该空间:

<p>
  <span> Foo </span><span> Bar </span>
</p>

I'm Looking for a CSS solution that doesn't involve:我正在寻找不涉及的 CSS 解决方案:

  • Altering the HTML.更改 HTML。
  • JavaScript. JavaScript。

Alternatively, you should now use flexbox to achieve many of the layouts that you may previously have used inline-block for: https://css-tricks.com/snippets/css/a-guide-to-flexbox/或者,您现在应该使用 flexbox来实现您以前使用 inline-block 的许多布局: https ://css-tricks.com/snippets/css/a-guide-to-flexbox/


Since this answer has become rather popular, I'm rewriting it significantly.由于这个答案已经变得相当流行,我正在重写它。

Let's not forget the actual question that was asked:我们不要忘记提出的实际问题:

How to remove the space between inline-block elements ?如何删除行内块元素之间的空间? I was hoping for a CSS solution that doesn't require the HTML source code to be tampered with.我希望有一个不需要篡改 HTML 源代码的 CSS 解决方案。 Can this issue be solved with CSS alone?这个问题可以单独用 CSS 解决吗?

It is possible to solve this problem with CSS alone, but there are no completely robust CSS fixes.单独使用 CSS 可以解决这个问题,但没有完全强大的 CSS 修复。

The solution I had in my initial answer was to add font-size: 0 to the parent element, and then declare a sensible font-size on the children.我最初回答的解决方案是将font-size: 0添加到父元素,然后在子元素上声明一个合理的font-size

http://jsfiddle.net/thirtydot/dGHFV/1361/ http://jsfiddle.net/thirtydot/dGHFV/1361/

This works in recent versions of all modern browsers.这适用于所有现代浏览器的最新版本。 It works in IE8.它适用于 IE8。 It does not work in Safari 5, but it does work in Safari 6. Safari 5 is nearly a dead browser ( 0.33%, August 2015 ).它在 Safari 5中不起作用,但在 Safari 6 中起作用。Safari 5 几乎是一个死浏览器( 0.33%,2015 年 8 月)。

Most of the possible issues with relative font sizes are not complicated to fix.相对字体大小的大多数可能问题并不复杂。

However, while this is a reasonable solution if you specifically need a CSS only fix, it's not what I recommend if you're free to change your HTML (as most of us are).但是,如果您特别需要仅修复 CSS,这是一个合理的解决方案,但如果您可以随意更改 HTML(就像我们大多数人一样),我不建议您这样做。


This is what I, as a reasonably experienced web developer, actually do to solve this problem:这就是我,作为一个经验丰富的 Web 开发人员,实际解决这个问题的方法:

<p>
    <span>Foo</span><span>Bar</span>
</p>

Yes, that's right.是的,这是正确的。 I remove the whitespace in the HTML between the inline-block elements.我删除了 HTML 中内联块元素之间的空格。

It's easy.这很简单。 It's simple.这很简单。 It works everywhere.它无处不在。 It's the pragmatic solution.这是务实的解决方案。

You do sometimes have to carefully consider where whitespace will come from.您有时必须仔细考虑空白的来源。 Will appending another element with JavaScript add whitespace?用 JavaScript 添加另一个元素会添加空格吗? No, not if you do it properly.不,如果你做得好,就不会。

Let's go on a magical journey of different ways to remove the whitespace, with some new HTML:让我们开始一段神奇的旅程,使用一些新的 HTML 来去除空格:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
</ul>
  • You can do this, as I usually do:你可以这样做,就像我通常做的那样:

     <ul> <li>Item 1</li><li>Item 2</li><li>Item 3</li> </ul>

http://jsfiddle.net/thirtydot/dGHFV/1362/ http://jsfiddle.net/thirtydot/dGHFV/1362/

  • Or, this:或这个:

     <ul> <li>Item 1</li ><li>Item 2</li ><li>Item 3</li> </ul>
  • Or, use comments:或者,使用注释:

     <ul> <li>Item 1</li><!-- --><li>Item 2</li><!-- --><li>Item 3</li> </ul>
  • Or, if you are using using PHP or similar:或者,如果您使用的是 PHP 或类似的:

     <ul> <li>Item 1</li><? ?><li>Item 2</li><? ?><li>Item 3</li> </ul>
  • Or, you can even skip certain closing tags entirely (all browsers are fine with this):或者, 您甚至可以完全跳过某些结束标签(所有浏览器都可以这样做):

     <ul> <li>Item 1 <li>Item 2 <li>Item 3 </ul>

Now that I've gone and bored you to death with "one thousand different ways to remove whitespace, by thirtydot", hopefully you've forgotten all about font-size: 0 .既然我已经用“一千种不同的方法来删除空白,三十点”让你厌烦至死,希望你已经忘记了关于font-size: 0一切。

For CSS3 conforming browsers there is white-space-collapsing:discard对于符合 CSS3 的浏览器,有white-space-collapsing:discard

see: http://www.w3.org/TR/2010/WD-css3-text-20101005/#white-space-collapsing见: http ://www.w3.org/TR/2010/WD-css3-text-20101005/#white-space-collapsing

Today, we should just use Flexbox .今天,我们应该只使用Flexbox


OLD ANSWER:旧答案:

OK, although I've upvoted both the font-size: 0;好的,尽管我对font-size: 0;都投了赞成票and the not implemented CSS3 feature answers, after trying I found out that none of them is a real solution .以及not implemented CSS3 feature答案,在尝试后我发现它们都不是真正的解决方案

Actually, there is not even one workaround without strong side effects.实际上,甚至没有一种解决方法没有强烈的副作用。

Then I decided to remove the spaces (this answers is about this argument) between the inline-block divs from my HTML source ( JSP ), turning this:然后我决定从我的HTML源代码( JSP )中删除inline-block div 之间的空格(这个答案是关于这个参数的),将其变为:

<div class="inlineBlock">
    I'm an inline-block div
</div>
<div class="inlineBlock">
    I'm an inline-block div
</div>

to this对此

<div class="inlineBlock">
    I'm an inline-block div
</div><div class="inlineBlock">
    I'm an inline-block div
</div>

that is ugly, but working.那很丑陋,但是可以工作。

But, wait a minute... what if I'm generating my divs inside Taglibs loops ( Struts2 , JSTL , etc...) ?但是,等一下……如果我在Taglibs loopsStruts2JSTL等)中生成我的 div 怎么办?

For example:例如:

<s:iterator begin="0" end="6" status="ctrDay">
    <br/>
    <s:iterator begin="0" end="23" status="ctrHour">
        <s:push value="%{days[#ctrDay.index].hours[#ctrHour.index]}">
            <div class="inlineBlock>
                I'm an inline-block div in a matrix 
                (Do something here with the pushed object...)
           </div>
       </s:push>
    </s:iterator>
</s:iterator>

It is absolutely not thinkable to inline all that stuff, it would mean内联所有这些东西是绝对不可想象的,这意味着

<s:iterator begin="0" end="6" status="ctrDay">
    <br/>
    <s:iterator begin="0" end="23" status="ctrHour"><s:push value="%{days[#ctrDay.index].hours[#ctrHour.index]}"><div class="inlineBlock>
                I'm an inline-block div in a matrix             
                (Do something here with the pushed object...)
           </div></s:push></s:iterator>
</s:iterator>

That is not readable, hard to maintain and understand, etc.这不可读,难以维护和理解等。

The solution I found:我找到的解决方案:

use HTML comments to connect the end of one div to the begin of the next one!使用 HTML 注释将一个 div 的结尾连接到下一个 div 的开头!

<s:iterator begin="0" end="6" status="ctrDay">
   <br/>
   <s:iterator begin="0" end="23" status="ctrHour"><!--
    --><s:push value="%{days[#ctrDay.index].hours[#ctrHour.index]}"><!--
        --><div class="inlineBlock>
                I'm an inline-block div in a matrix             
                (Do something here with the pushed object...)
           </div><!--
    --></s:push><!--
--></s:iterator>
</s:iterator>

This way you will have a readable and correctly indented code.这样,您将拥有可读且正确缩进的代码。

And, as a positive side effect, the HTML source , although infested by empty comments, will result correctly indented;并且,作为一个积极的副作用, HTML source虽然被空注释侵扰,但会导致正确缩进;

let's take the first example.让我们举第一个例子。 In my humble opinion, this:以我的拙见,这是:

    <div class="inlineBlock">
        I'm an inline-block div
    </div><!--
 --><div class="inlineBlock">
        I'm an inline-block div
    </div>

is better than this:比这更好:

    <div class="inlineBlock">
         I'm an inline-block div
    </div><div class="inlineBlock">
         I'm an inline-block div
    </div>

Add display: flex;添加display: flex; to the parent element.到父元素。 Here is the solution with a prefix:这是带有前缀的解决方案:

Simplified version 👇简化版👇

 p { display: flex; } span { width: 100px; background: tomato; font-size: 30px; color: white; text-align: center; }
 <p> <span> Foo </span> <span> Bar </span> </p>


Fix with prefix 👇修复前缀👇

 p { display: -webkit-box; display: -webkit-flex; display: -ms-flexbox; display: flex; } span { float: left; display: inline-block; width: 100px; background: blue; font-size: 30px; color: white; text-align: center; }
 <p> <span> Foo </span> <span> Bar </span> </p>

All the space elimination techniques for display:inline-block are nasty hacks...所有用于display:inline-block的空间消除技术都是讨厌的 hack ......

Use Flexbox使用弹性盒

It's awesome, solves all this inline-block layout bs, and as of 2017 has 98% browser support (more if you don't care about old IEs).太棒了,解决了所有这些 inline-block 布局 bs,并且截至 2017 年有98% 的浏览器支持(如果你不关心旧的 IE 则更多)。

Add comments between elements to NOT have a white space.在元素之间添加注释以不包含空格。 For me it is easier than resetting font size to zero and then setting it back.对我来说,这比将字体大小重置为零然后重新设置要容易。

<div>
    Element 1
</div><!--
--><div>
    Element 2
</div>

This is the same answer I gave over on the related: Display: Inline block - What is that space?这与我在相关方面给出的答案相同: 显示:内联块-那个空间是什么?

There's actually a really simple way to remove whitespace from inline-block that's both easy and semantic.实际上有一种非常简单的方法可以从 inline-block 中删除空格,既简单又符合语义。 It's called a custom font with zero-width spaces, which allows you to collapse the whitespace (added by the browser for inline elements when they're on separate lines) at the font level using a very tiny font.它被称为具有零宽度空格的自定义字体,它允许您使用非常小的字体在字体级别折叠空格(当内联元素位于单独的行时由浏览器添加)。 Once you declare the font, you just change the font-family on the container and back again on the children, and voila.声明字体后,只需更改容器上的font-family ,然后再更改子代,瞧。 Like this:像这样:

@font-face{ 
    font-family: 'NoSpace';
    src: url('../Fonts/zerowidthspaces.eot');
    src: url('../Fonts/zerowidthspaces.eot?#iefix') format('embedded-opentype'),
         url('../Fonts/zerowidthspaces.woff') format('woff'),
         url('../Fonts/zerowidthspaces.ttf') format('truetype'),
         url('../Fonts/zerowidthspaces.svg#NoSpace') format('svg');
}

body {
    font-face: 'OpenSans', sans-serif;
}

.inline-container {
    font-face: 'NoSpace';
}

.inline-container > * {
    display: inline-block;
    font-face: 'OpenSans', sans-serif;
}

Suit to taste.适合口味。 Here's a download to the font I just cooked up in font-forge and converted with FontSquirrel webfont generator.这是我刚刚在 font-forge 中制作并使用 FontSquirrel webfont 生成器转换的字体的下载。 Took me all of 5 minutes.花了我5分钟。 The css @font-face declaration is included: zipped zero-width space font .包含 css @font-face声明: zipped zero-width space font It's in Google Drive so you'll need to click File > Download to save it to your computer.它位于 Google 云端硬盘中,因此您需要单击“文件”>“下载”将其保存到您的计算机上。 You'll probably need to change the font paths as well if you copy the declaration to your main css file.如果将声明复制到主 css 文件,您可能还需要更改字体路径。

2021 Solution 2021解决方案

Unfortunately white-space-collapse is still not implemented.不幸的是white-space-collapse仍然没有实现。

In the meantime, give the parent element font-size: 0;同时,给父元素font-size: 0; and set the font-size on the children.并设置孩子的font-size This should do the trick这应该可以解决问题

Two more options based on CSS Text Module Level 3 (instead of white-space-collapsing:discard which had been dropped from the spec draft):基于CSS Text Module Level 3的另外两个选项(而不是从规范草案中删除的white-space-collapsing:discard ):

  • word-spacing: -100%;

In theory, it should do exactly what is needed — shorten whitespaces between 'words' by the 100% of the space character width, ie to zero.理论上,它应该完全满足需要——将“单词”之间的空格缩短 100% 的空格字符宽度,即为零。 But seems not to work anywhere, unfortunately, and this feature is marked 'at risk' (it can be dropped from the specification, too).但不幸的是,它似乎在任何地方都不起作用,并且这个特性被标记为“有风险”(它也可以从规范中删除)。

  • word-spacing: -1ch;

It shortens the inter-word spaces by the width of the digit '0'.它将字间距缩短了数字“0”的宽度。 In a monospace font it should be exactly equal to the width of the space character (and any other character as well).在等宽字体中,它应该完全等于空格字符(以及任何其他字符)的宽度。 This works in Firefox 10+, Chrome 27+, and almost works in Internet Explorer 9+.这适用于 Firefox 10+、Chrome 27+,并且几乎适用于 Internet Explorer 9+。

Fiddle小提琴

Use flexbox and do a fallback (from suggestions above) for older browsers:使用 flexbox 并为旧浏览器做一个后备(根据上面的建议):

ul {
    display: -webkit-box;
    display: -moz-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
}

Though, technically not an answer to the question: "How do I remove the space between inline-block elements?"不过,从技术上讲,这不是问题的答案:“如何删除内联块元素之间的空间?”

You can try the flexbox solution and apply the code below and the space will be remove.您可以尝试 flexbox 解决方案并应用下面的代码,空间将被删除。

p {
   display: flex;
   flex-direction: row;
}

You can learn more about it on this link: https://css-tricks.com/snippets/css/a-guide-to-flexbox/您可以在此链接上了解更多信息: https ://css-tricks.com/snippets/css/a-guide-to-flexbox/

Simple:简单的:

item {
  display: inline-block;
  margin-right: -0.25em;
}

There is no need to touch the parent element.无需触摸父元素。

Only condition here: the item's font-size must not be defined (must be equal to parent's font-size).此处的唯一条件:不得定义项目的字体大小(必须等于父项的字体大小)。

0.25em is the default word-spacing 0.25em是默认word-spacing

W3Schools - word-spacing property W3Schools - 字间距属性

font-size:0;字体大小:0; can be a bit trickier to manage...管理起来可能有点棘手……

I think the following couple lines is a lot better and more re-usable, and time saver than any other methods.我认为以下几行比任何其他方法都更好,更可重用,并且更节省时间。 I personally use this:我个人使用这个:

.inline-block-wrapper>.inline-block-wrapper,
.inline-block-wrapper{letter-spacing: -4px;}
.inline-block-wrapper>*{letter-spacing: 0;display: inline-block;}

/* OR better shorter name...*/
.items>.items,
.items{letter-spacing: -4px;}
.items>*{letter-spacing: 0;display: inline-block;}

Then you can use it as following...然后你可以使用它如下...

<ul class="items">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
</ul>

As far I as I know (I may be wrong) but all browsers support this method.据我所知(我可能错了),但所有浏览器都支持这种方法。

EXPLANATION :解释

This works (maybe -3px may be better) exactly as you would anticipate it to work.这完全符合您的预期(也许 -3px 可能会更好)。

  • you copy and paste the code (once)您复制并粘贴代码(一次)
  • then on your html just use class="items" on the parent of each inline-block.然后在您的 html 上,只需在每个内联块的父级上使用class="items"即可。

You will NOT have the need to go back to the css, and add another css rule, for your new inline blocks.您无需返回 css 并为新的内联块添加另一个 css 规则。

Solving two issues at once.一次解决两个问题。

Also note the > (greater than sign) this means that */all children should be inline-block.另请注意> (大于符号)这意味着 */all 子项应该是内联块。

http://jsfiddle.net/fD5u3/ http://jsfiddle.net/fD5u3/

NOTE: I have modified to accommodate to inherit letter-spacing when a wrapper has a child wrapper.注意:当包装器具有子包装器时,我已经修改以适应继承字母间距。

Generally we use elements like this in different lines, but in case of display:inline-block using tags in same line will remove the space, but in a different line will not.通常我们在不同的行中使用这样的元素,但是在display:inline-block的情况下,在同一行使用标签会删除空格,但在不同的行不会。

An example with tags in a different line:不同行中带有标签的示例:

 p span { display: inline-block; background: red; }
 <p> <span> Foo </span> <span> Bar </span> </p>

Example with tags in same line同一行中带有标签的示例

 p span { display: inline-block; background: red; }
 <p> <span> Foo </span><span> Bar </span> </p>


Another efficient method is a CSS job that is using font-size:0 to the parent element and give font-size to a child element as much as you want.另一种有效的方法是 CSS 作业,它将font-size:0用于父元素,并根据需要为子元素提供font-size

 p { font-size: 0; } p span { display: inline-block; background: red; font-size: 14px; }
 <p> <span> Foo </span> <span> Bar </span> </p>

The above methods may not work somewhere depending on the whole application, but the last method is a foolproof solution for this situation and can be used anywhere.根据整个应用程序,上述方法可能在某些地方不起作用,但最后一种方法是针对这种情况的万无一失的解决方案,可以在任何地方使用。

I'm not pretty sure if you want to make two blue spans without a gap or want to handle other white-space, but if you want to remove the gap:我不太确定您是要制作两个没有间隙的蓝色跨度还是要处理其他空白,但是如果您想消除间隙:

span {
    display: inline-block;
    width: 100px;
    background: blue;
    font-size: 30px;
    color: white;
    text-align: center;

    float: left;
}

And done.并做了。

I had this problem right now and from font-size:0;我现在遇到了这个问题,来自font-size:0; I've found that in Internet Explorer 7 the problem remains because Internet Explorer thinks "Font Size 0?!?! WTF are you crazy man?"我发现在 Internet Explorer 7 中问题仍然存在,因为 Internet Explorer 认为“字体大小为 0?!?!WTF 你是疯子吗?” - So, in my case I've Eric Meyer's CSS reset and with font-size:0.01em; - 所以,在我的情况下,我重置了 Eric Meyer 的 CSS 并使用font-size:0.01em; I have a difference of 1 pixel from Internet Explorer 7 to Firefox 9, so, I think this can be a solution.我从 Internet Explorer 7 到 Firefox 9 有 1 个像素的差异,所以,我认为这可能是一个解决方案。

 p { display: flex; } span { float: left; display: inline-block; width: 100px; background: red; font-size: 30px; color: white; }
 <p> <span> hello </span> <span> world </span> </p>

I've been tackling this recently and instead of setting the parent font-size:0 then setting the child back to a reasonable value, I've been getting consistent results by setting the parent container letter-spacing:-.25em then the child back to letter-spacing:normal .我最近一直在解决这个问题,而不是设置父font-size:0然后将子设置回一个合理的值,而是通过设置父容器letter-spacing:-.25em然后设置子来获得一致的结果回到letter-spacing:normal

In an alternate thread I saw a commenter mention that font-size:0 isn't always ideal because people can control minimum font sizes in their browsers, completely negating the possibility of setting the font-size to zero.在另一个线程中,我看到一位评论者提到font-size:0并不总是理想的,因为人们可以控制浏览器中的最小字体大小,完全否定了将 font-size 设置为零的可能性。

Using ems appears to work regardless of whether the font-size specified is 100%, 15pt or 36px.无论指定的字体大小是 100%、15pt 还是 36px,使用 ems 似乎都有效。

http://cdpn.io/dKIjo http://cdpn.io/dKIjo

I think there is a very simple/old method for this which is supported by all browsers even IE 6/7.我认为有一个非常简单/旧的方法,所有浏览器甚至 IE 6/7 都支持它。 We could simply set letter-spacing to a large negative value in parent and then set it back to normal at child elements:我们可以简单地在父元素中将letter-spacing设置为较大的负值,然后在子元素中将其恢复为normal

 body { font-size: 24px } span { border: 1px solid #b0b0c0; } /* show borders to see spacing */ .no-spacing { letter-spacing: -1em; } /* could be a large negative value */ .no-spacing > * { letter-spacing: normal; } /* => back to normal spacing */
 <p style="color:red">Wrong (default spacing):</p> <div class=""> <span>Item-1</span> <span>Item-2</span> <span>Item-3</span> </div> <hr/> <p style="color:green">Correct (no-spacing):</p> <div class="no-spacing"> <span>Item-1</span> <span>Item-2</span> <span>Item-3</span> </div>

The simplest answer to this question is to add.这个问题最简单的答案是添加。

css css

float: left;

codepen link: http://jsfiddle.net/dGHFV/3560/代码笔链接:http: //jsfiddle.net/dGHFV/3560/

With PHP brackets:使用 PHP 括号:

 ul li { display: inline-block; }
 <ul> <li> <div>first</div> </li><? ?><li> <div>first</div> </li><? ?><li> <div>first</div> </li> </ul>

I'm going to expand on user5609829's answer a little bit as I believe the other solutions here are too complicated/too much work.我将稍微扩展 user5609829 的答案,因为我认为这里的其他解决方案太复杂/工作量太大。 Applying a margin-right: -4px to the inline block elements will remove the spacing and is supported by all browsers.对内联块元素应用margin-right: -4px将删除间距并且所有浏览器都支持。 See the updated fiddle here .此处查看更新的小提琴。 For those concerned with using negative margins, try giving this a read.对于那些关心使用负边距的人,请尝试阅读内容。

I found a pure CSS solution that worked for me very well in all browsers:我找到了一个在所有浏览器中都非常适合我的纯 CSS 解决方案:

span {
    display: table-cell;
}

Add white-space: nowrap to the container element:添加white-space: nowrap到容器元素:

CSS: CSS:

* {
    box-sizing: border-box;
}
.row {
    vertical-align: top;
    white-space: nowrap;
}
.column{
    float: left;
    display: inline-block;
    width: 50% // Or whatever in your case
}

HTML: HTML:

<div class="row">
    <div class="column"> Some stuff</div>
    <div class="column">Some other stuff</div>
</div>

Here is the Plunker .这是Plunker

The CSS Text Module Level 4 specification defines a text-space-collapse property, which allow to control the how white space inside and around an element is processed. CSS Text Module Level 4 规范定义了一个text-space-collapse属性,它允许控制如何处理元素内部和周围的空白。

So, regarding your example, you would just have to write this:所以,关于你的例子,你只需要这样写:

p {
  text-space-collapse: discard;
}

Unfortunately, no browser is implementing this property yet (as of September 2016) as mentioned in the comments to the answer of HBP .不幸的是,正如对 HBP 答案的评论中提到的那样,还没有浏览器实现此属性(截至 2016 年 9 月)。

There are lots of solutions like font-size:0 , word-spacing , margin-left , letter-spacing and so on.有很多解决方案,例如font-size:0word-spacingmargin-leftletter-spacing等。

Normally I prefer using letter-spacing because通常我更喜欢使用letter-spacing ,因为

  1. it seems ok when we assign a value which is bigger than the width of extra space(eg -1em ).当我们分配一个大于额外空间宽度的值时(例如-1em )似乎没问题。
  2. However, it won't be okay with word-spacing and margin-left when we set bigger value like -1em .但是,当我们设置较大的值(如-1em )时, word-spacingmargin-left就不行了。
  3. Using font-size is not convenient when we try to using em as font-size unit.当我们尝试使用em作为font-size单位时,使用font-size并不方便。

So, letter-spacing seems to be the best choice.因此, letter-spacing似乎是最佳选择。

However, I have to warn you但是,我必须警告你

when you using letter-spacing you had better using -0.3em or -0.31em not others.当您使用letter-spacing时,最好使用-0.3em-0.31em而不是其他。

 * { margin: 0; padding: 0; } a { text-decoration: none; color: inherit; cursor: auto; } .nav { width: 260px; height: 100px; background-color: pink; color: white; font-size: 20px; letter-spacing: -1em; } .nav__text { width: 90px; height: 40px; box-sizing: border-box; border: 1px solid black; line-height: 40px; background-color: yellowgreen; text-align: center; display: inline-block; letter-spacing: normal; }
 <nav class="nav"> <span class="nav__text">nav1</span> <span class="nav__text">nav2</span> <span class="nav__text">nav3</span> </nav>

If you are using Chrome(test version 66.0.3359.139) or Opera(test version 53.0.2907.99), what you see might be:如果您使用的是 Chrome(测试版 66.0.3359.139)或 Opera(测试版 53.0.2907.99),您看到的可能是:

在此处输入图像描述

If you are using Firefox(60.0.2),IE10 or Edge, what you see might be:如果您使用的是 Firefox(60.0.2)、IE10 或 Edge,您看到的可能是:

在此处输入图像描述

That's interesting.那很有意思。 So, I checked themdn-letter-spacing and found this:所以,我检查了mdn-letter-spacing并发现了这个:

length长度

Specifies extra inter-character space in addition to the default space between characters.除了字符之间的默认空间之外,还指定额外的字符间空间。 Values may be negative, but there may be implementation-specific limits.值可能为负,但可能存在特定于实现的限制。 User agents may not further increase or decrease the inter-character space in order to justify text.用户代理可能不会进一步增加或减少字符间距来证明文本的合理性。

It seems that this is the reason.似乎这就是原因。

Add letter-spacing:-4px;添加letter-spacing:-4px; on parent p css and add letter-spacing:0px;在父p css 上并添加letter-spacing:0px; to your span css.到你的span css。

 span { display:inline-block; width:100px; background-color:palevioletred; vertical-align:bottom; letter-spacing:0px; } p { letter-spacing:-4px; }
 <p> <span> Foo </span> <span> Bar </span> </p>

I thought I'd add something new to this question as although many of the answers currently provided are more than adequate & relevant, there are some new CSS properties which can achieve a very clean output, with full support across all browsers, and little to no 'hacks'.我想我会为这个问题添加一些新的东西,因为虽然目前提供的许多答案都已经足够且相关,但有一些新的 CSS 属性可以实现非常干净的输出,完全支持所有浏览器,而且几乎没有没有“黑客”。 This does move away from inline-block but it gives you the same results as the question asked for.这确实远离了inline-block ,但它为您提供了与所要求的问题相同的结果。

These CSS properties are grid这些 CSS 属性是grid

CSS Grid is highly supported ( CanIUse ) apart from IE which only needs an -ms- prefix to allow for it to work. CSS Grid 得到高度支持( CanIUse ),除了 IE,它只需要一个-ms-前缀就可以工作。

CSS Grid is also highly flexible, and takes all the good parts from table , flex , and inline-block elements and brings them into one place. CSS Grid 也是高度灵活的,它从tableflexinline-block元素中提取所有好的部分并将它们集中到一个位置。

When creating a grid you can specify the gaps between the rows and columns.创建grid时,您可以指定行和列之间的间隙。 The default gap is already set to 0px but you can change this value to whatever you like.默认间隙已设置为0px ,但您可以将此值更改为您喜欢的任何值。

To cut it a bit short, heres a relevant working example:简而言之,这是一个相关的工作示例:

 body { background: lightblue; font-family: sans-serif; } .container { display: grid; grid-template-columns: 100px 100px; grid-column-gap: 0; /* Not needed but useful for example */ grid-row-gap: 0; /* Not needed but useful for example */ } .box { background: red; } .box:nth-child(even) { background: green; }
 <div class="container"> <div class="box"> Hello </div> <div class="box"> Test </div> </div>

Negative margin负边距

You can scoot the elements back into place with negative 4px of margin (may need to be adjusted based on font size of parent).您可以使用负 4px 的边距将元素滑回原位(可能需要根据父级的字体大小进行调整)。 Apparently this is problematic in older IE (6 & 7), but if you don't care about those browsers at least you can keep the code formatting clean.显然这在较旧的 IE(6 和 7)中是有问题的,但如果您不关心这些浏览器,至少您可以保持代码格式干净。

span {
  display: inline-block;
  margin-right: -4px;
}

Remove the spaces from inline block elements, there are so many methods:从内联块元素中删除空格,有很多方法:

  1. Font size to zero字体大小为零

    nav { font-size: 0; } nav a { font-size: 16px; }
  2. Negative margin负边距

    div a { display: inline-block; margin-right: -4px; }
  3. Skip the closing tag跳过结束标签

    <ul> <li> one <li> two <li> three </ul>
  4. Use comments:使用注释:

    <ul> <li>Item 1</li><!-- --><li>Item 2</li><!-- --><li>Item 3</li> </ul>

One another way I found is applying margin-left as negative values except the first element of the row.我发现的另一种方法是将 margin-left 作为负值应用,除了行的第一个元素。

span { 
 display:inline-block;
 width:100px;
 background:blue;
 font-size:30px;
 color:white; 
 text-align:center;
 margin-left:-5px;
}
span:first-child{
 margin:0px;
}

I tried out the font-size: 0 solution to a similar problem in React and Sass for a Free Code Camp project I am currently working through.我为我目前正在处理的一个 Free Code Camp 项目尝试了font-size: 0解决方案来解决 React 和Sass中的类似问题。

And it works!它有效!

First, the script:首先,脚本:

var ActionBox = React.createClass({
    render: function() {
        return(
            <div id="actionBox">
                </div>
        );
    },
});

var ApplicationGrid = React.createClass({
    render: function() {
        var row = [];
        for(var j=0; j<30; j++){
            for(var i=0; i<30; i++){
                row.push(<ActionBox />);
            }
        }
        return(
            <div id="applicationGrid">
                {row}
            </div>
        );
     },
});

var ButtonsAndGrid = React.createClass({
    render: function() {
        return(
            <div>
                <div id="buttonsDiv">
                </div>
                <ApplicationGrid />
            </div>
        );
    },
});

var MyApp = React.createClass({
    render: function() {
        return(
            <div id="mainDiv">
                <h1> Game of Life! </h1>
                <ButtonsAndGrid />
            </div>
        );
    },
});

ReactDOM.render(
    <MyApp />,
    document.getElementById('GoL')
);

Then, the Sass:然后,萨斯:

html, body
    height: 100%

body
    height: 100%
    margin: 0
    padding: 0

#mainDiv
    width: 80%
    height: 60%
    margin: auto
    padding-top: 5px
    padding-bottom: 5px
    background-color: DeepSkyBlue
    text-align: center
    border: 2px solid #381F0B
    border-radius: 4px
    margin-top: 20px

#buttonsDiv
    width: 80%
    height: 60%
    margin: auto
    margin-bottom: 0px
    padding-top: 5px
    padding-bottom: 0px
    background-color: grey
    text-align: center
    border: 2px solid #381F0B
    border-radius: 4px
    margin-top: 20px

#applicationGrid
    width: 65%
    height: 50%
    padding-top: 0px
    margin: auto
    font-size: 0
    margin-top: 0px
    padding-bottom: 5px
    background-color: white
    text-align: center
    border: 2px solid #381F0B
    border-radius: 4px
    margin-top: 20px

#actionBox
    width: 20px
    height: 20PX
    padding-top: 0px
    display: inline-block
    margin-top: 0px
    padding-bottom: 0px
    background-color: lightgrey
    text-align: center
    border: 2px solid grey
    margin-bottom: 0px

Every question, that try to remove the space between inline-block s seems like a <table> to me...每一个试图删除inline-block之间空格的问题对我来说都像是一个<table> ......

Try something like this:尝试这样的事情:

 p { display: table; } span { width: 100px; border: 1px solid silver; /* added for visualization only*/ display: table-cell; }
 <p> <span> Foo </span> <span> Bar </span> </p>

Just for fun: an easy JavaScript solution.只是为了好玩:一个简单的 JavaScript 解决方案。

 document.querySelectorAll('.container').forEach(clear); function clear(element) { element.childNodes.forEach(check, element); } function check(item) { if (item.nodeType === 3) this.removeChild(item); }
 span { display: inline-block; width: 100px; background-color: palevioletred; }
 <p class="container"> <span> Foo </span> <span> Bar </span> </p>

Use one of these tricks使用这些技巧之一

  1. Remove the spaces删除空格
  2. Negative margin负边距
  3. Skip the closing tag (HTML5 doesn't care anyway)跳过结束标签(HTML5 无论如何都不关心)
  4. Set the font size to zero (A space that has zero font-size is... zero width)将字体大小设置为零(字体大小为零的空间是......零宽度)
  5. Use flexbox使用弹性盒

See the code below:请看下面的代码:

 body { font-family: sans-serif; font-size: 16px; } ul { list-style: none } li { background: #000; display: inline-block; padding: 4px; color: #fff; } ul.white-space-fix li { margin-right: -4px; } ul.zero-size { font-size: 0px; } ul.zero-size li { font-size: 16px; } ul.flexbox { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; }
 original... <ul> <li>one</li> <li>two</li> <li>three</li> </ul> Funky code formatting... <ul> <li> one</li><li> two</li><li> three</li> </ul> Adding html comments... <ul> <li>one</li><!-- --><li>two</li><!-- --><li>three</li> </ul> CSS margin-right: -4px; <ul class="white-space-fix"> <li>one</li> <li>two</li> <li>three</li> </ul> Omitting the &lt;/li&gt; <ul> <li>one <li>two <li>three </ul> fixed with font-size: 0 <br><br> <ul class="zero-size"> <li>one</li> <li>two</li> <li>three</li> </ul> <br> flexbox <br> <ul class="flexbox"> <li>one</li> <li>two</li> <li>three</li> </ul>

If you're using Twig template engine, you can use spaceless :如果您使用的是 Twig 模板引擎,则可以使用spaceless

<p>
    {% spaceless %}
    <span>Foo</span>
    <span>Bar</span>
    {% endspaceless %}
</p>

Note whilst this doesn't address the exact question asked, this could be useful if someone has Twig at their disposal, to avoid using some lesser solution.请注意,虽然这不能解决所提出的确切问题,但如果有人可以使用 Twig,这可能会很有用,以避免使用一些较小的解决方案。

Why not something like this... a bit hacky, and depends on your code for the css units, but:为什么不这样......有点hacky,并且取决于您的css单元代码,但是:

.my-span {
    position: relative;
    left: -1em;
    width: 1em;
}
<span>...</span><span class="my-span"></span>

There is a easy solution in CSS. CSS中有一个简单的解决方案。 For example:例如:

HTML HTML

<p class="parent">
    <span class="children"> Foo </span>
    <span class="children"> Bar </span>
</p>

CSS CSS

.parent {
    letter-spacing: -.31em;
    *letter-spacing: normal;
    *word-spacing: -.43em;
}
.children {
    display: inline-block;
    *display: inline;
    zoom: 1;
    letter-spacing: normal;
    word-spacing: normal;
}

In my opinion writing font-size: 0 is not safe when you use it in a project like em , so I prefer purecss' solution.在我看来,在像em这样的项目中使用font-size: 0是不安全的,所以我更喜欢 purecss 的解决方案。

You can check this framework in this link purecss .您可以在此链接purecss中检查此框架。 Enjoy :)享受:)

 .row { letter-spacing: -.31em; *letter-spacing: normal; *word-spacing: -.43em; /* For better view */ background: #f9f9f9; padding: 1em .5em; } .col { display: inline-block; *display: inline; zoom: 1; letter-spacing: normal; word-spacing: normal; /* For better view */ padding: 16px; background: #dbdbdb; border: 3px #bdbdbd solid; box-sizing: border-box; width: 25%; }
 <div class="row"> <div class="col">1</div> <div class="col">2</div> <div class="col">3</div> <div class="col">4</div> </div>

Try this snippet:试试这个片段:

span {
    display: inline-block;
    width: 100px;
    background: blue;
    font-size: 30px;
    color: white;
    text-align: center;
    margin-right: -3px;
}

Working demo: http://jsfiddle.net/dGHFV/2784/工作演示:http: //jsfiddle.net/dGHFV/2784/

 span { display:inline-block; width:50px; background:blue; font-size:30px; color:white; text-align:center; }
 <p><span>Foo</span><span>Bar</span></p>

So a lot of complicated answers.所以很多复杂的答案。 The easiest way I can think of is to just give one of the elements a negative margin (either margin-left or margin-right depending on the position of the element).我能想到的最简单的方法是只给一个元素一个负边距( margin-leftmargin-right取决于元素的位置)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM