防止:元素从包装到下一行之后

我有这个HTML:

<ul> <li class="completed"><a href="#">I want the icon to stay on the same line as this last <strong>word</strong></li> </ul> 

我使用:after伪元素追加一个图标:

 ul li.completed a:after { background:transparent url(img.png) no-repeat; content: ''; display:inline-block; width: 24px; height: 16px; } 

问题是:如果可用的宽度太小,图标将换行到下一行。 我希望它保持在它所附加的链接的最后一个字的同一行上:

在这里输入图像说明

这是可行的,没有添加“nowrap”的整个链接(我想单词包装,而不是图标)。

在这里看到j​​sFiddle。

您可以将图像添加到最后一个单词中。 这将使它一起破裂。

为单词<strong class="test">word</strong>添加一个类

.test:after { ...

http://jsfiddle.net/52dkR/

诀窍还是让这个类是inline-block

如果你想保持下划线看到这一点。

http://jsfiddle.net/atcJJ/

添加text-decoration:inherit;

JSFiddle – http://jsfiddle.net/Bk38F/65/

向伪元素添加负余量,以补偿其宽度:

 ul li.completed a:before { background:transparent url(img1.png) no-repeat; content: ' '; display: inline-block; width: 24px; height: 16px; margin-right: -24px; } 

现在,这将使图标溢出容器,只有当文本遇到行结束时,行才会中断。 如果您需要将图标保留在原始容器宽度内,则可以添加填充以进行补偿:

 ul li.completed a { display: inline-block; padding-right: 24px; } 

重要更新:

为了使这个方法起作用,在保持伪元素的元素的文本和结束标记之间不能有空格。 即使伪元素的宽度被负边距补偿,当空白符合父元素的边缘时,它将使线条断裂。 例如,这工作:

 <span>text goes here</span> 

 <span> text goes here </span> 

我有同样的问题。 我不太喜欢在最后一个单词中添加strong或span标签的想法,所以我试着简单地将图标作为背景图像添加一些填充,而不是使用:after或:before伪元素。 为我工作!

 <ul><li class="completed"><a href="#">I want the icon to stay on the same line as this last word</a></li></ul> 

 ul li.completed a { background: url(img1.png) no-repeat 100% 50%; padding-right: 18px; } 

http://jsfiddle.net/atcJJ/36/

请确保您之前结束标签

 <ul><li class="completed"><a href="#">I want the icon to stay on the same line as this last <strong>word</strong></a></li></ul> 

尝试下面的CSS。 而不是使用“之后”使用“之前”,并正确地浮动。

 ul li.completed a:before { background:transparent url(img1.png) no-repeat; content: ''; display:inline-block; width: 24px; height: 16px; float:right; } 

请检查这个: http : //jsfiddle.net/supriti/atcJJ/7/

这和以前的回答有一点相似,但是我想我会充实并且充分地解释它。

只要设置display: inline-block:after变成非文本绑定元素。 这就是为什么它包装,为什么nowrap没有效果。 所以请单独display

由于默认情况下它是一个文本元素,只要内容之间没有空白,内容就会绑定到以前的文本。 所以不要添加任何内容,但要确保你有content: "" ,或者是display: none 。 唯一的问题是heightwidth是由content控制的,在这种情况下是折叠的。 所以width0height是线的高度。

使用填充来调整区域的大小; 左或右,没关系。 添加一点margin使图标不接触文字。 保持一切为相对大小( empt等),并使用background-size: contain ,以便图标与文本一起缩放,如表情符号或字体。 最后在你想要的background-position放置图标。

 ul li.completed a:after { content: ""; background: url('icon.svg'); background-size: contain; background-repeat: no-repeat; background-position: center center; margin-left: 0.2em; /* spacing*/ padding-right: 0.75em; /* sizing */ } 

我已经使用这个我的外部链接( a[href*="://"]:after ),并且在Firefox,Chrome和iOS中运行良好。 而且由于图标仍然是一个文本元素,甚至直接绑定文本,所以任何closures的标点符号也将包装。

有可能没有:after 。 具有背景的元素应该display:inline

 <h1><span>I want the icon to stay on the same line as this last word</span></h1> h1 span { padding-right: 24px; background: url('icon.svg') no-repeat right top; } 

http://jsfiddle.net/my97k7b1/