Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent line break between two elements in CSS

Tags:

css

whitespace

For some basic layout work I'm doing, I'd like links that immediately follow a price to always be shown on the same line as the price. The price text is wrapped in a <span class="price"> tag while the link uses the buy-link class as in <a href="/buy" class="buy-link">Buy Now</a>.

I'm looking for CSS that will automatically prevent line breaking between the span and a tag but I'm either missing something or it can't be done. I can easily prevent line breaks within the two tags - but not between them.

I want to avoid wrapping both tags in a span with a white-space: nowrap manually and use pure CSS if possible.

Update: The HTML looks something like the following. It's not the real code but very similar.

<style>
    .price{ font-weight: bold; }
    .buy-link{ color: green; }
</style>

<span class="price">$50</span> <a href="/buy" class="buy-link">Buy Now</a>

If the link happens to be near the page edge - or block edge in a <div> or <table> browsers will wrap the Buy Now link to the next line. Separating the two elements.

like image 962
Paul Alexander Avatar asked Mar 18 '10 23:03

Paul Alexander


People also ask

How do you prevent a line from breaking in CSS?

You can prevent line breaks and text wrapping for specific elements using the CSS white-space property.

How do I stop text from breaking in CSS?

If you want to prevent the text from wrapping, you can apply white-space: nowrap; Notice in HTML code example at the top of this article, there are actually two line breaks, one before the line of text and one after, which allow the text to be on its own line (in the code).

How do I make text stay on 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 elements stay on the same line?

To get all elements to appear on one line the easiest way is to: Set white-space property to nowrap on a parent element; Have display: inline-block set on all child elements.


2 Answers

Can't you nest the anchor inside the span, like

<span class="price"><a href="/buy" class="buy-link">Buy Now</a>&nbsp;Only $19.95!</span>

then set the span to white-space: nowrap?

like image 182
Robusto Avatar answered Oct 01 '22 02:10

Robusto


<span class="price">$50</span>&nbsp;<a href="/buy" class="buy-link">Buy Now</a>
like image 24
graphicdivine Avatar answered Oct 01 '22 02:10

graphicdivine