Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid line breaks after ":before" in CSS

On my website I'm using font icons for certain link types. These icons are added via :before CSS syntax.

a.some-link:before {
  font-family: icons;
  display: inline-block;
  padding-right: 0.3em;
  content: 'x';
}

However, when this link is at the beginning of a line, it's sometimes separated from its icon:

Separated icon from link

I tried adding white-space: nowrap to the CSS rule above but that didn't help.

How do I keep the icon and the text together? (CSS 3 is okay)

Note: I don't want to format the whole link with white-space: nowrap.

like image 914
Sebastian Krysmanski Avatar asked Feb 13 '13 10:02

Sebastian Krysmanski


People also ask

How do you prevent a line from breaking in CSS?

The white-space property has numerous options, all of which define how to treat white space inside a given element. Here, you have set white-space to nowrap , which will prevent all line breaks.

How do you prevent line breaks?

There are several ways to prevent line breaks in content. Using   is one way, and works fine between words, but using it between an empty element and some text does not have a well-defined effect. The same would apply to the more logical and more accessible approach where you use an image for an icon.

How do I keep text in one line in CSS?

If you want to limit the text length to one line, you can clip the line, display an ellipsis or a custom string. All these can be done with the CSS text-overflow property, which determines how the overflowed content must be signalled to the user.

How do you make a line not break in HTML?

The <nobr> HTML element prevents the text it contains from automatically wrapping across multiple lines, potentially resulting in the user having to scroll horizontally to see the entire width of the text.


2 Answers

Simply removing the display:inline-block; seems to fix this issue:

a.some-link:before {
    font-family: icons;
    padding-right: 0.3em;
    content: 'x';
}

JSFiddle.

Unfortunately, you need "display: inline-block" to show SVG. Simple solution is to put "display: inline-block" on the "a". This will cause your SVG to render properly AND it will keep your a:before and the a together on one line.

like image 164
James Donnelly Avatar answered Sep 16 '22 14:09

James Donnelly


It is much better to add nowrap rule to :before css:

white-space: nowrap;

UPD: http://jsfiddle.net/MMbKK/5/

The reason for nowrap rule is to work properly with image content in :before. Text content don't need this rule to stay near the main element.

like image 21
ornic Avatar answered Sep 18 '22 14:09

ornic