Michael Swarts
Michael Swarts

Reputation: 3921

How can I remove html on line wrap?

Suppose you have:

<h1>800.BUY.WIDG &ndash; Call&nbsp;Now!</h1>

But you want the &ndash; to appear only if the line doesn't wrap.

I could do this:

<h1>800.BUY.WIDG</h1> <span class="stylistic_ndash">&ndash;</span> <h1>Call&nbsp;Now!</h1>

Then I could use media queries to remove the span element when the line would wrap.

The problem is that this approach quickly becomes untenable when there's several items like this on a page that each wrap at different viewport widths. Is there a better way?

Thanks!

Upvotes: 0

Views: 77

Answers (1)

Blake Mann
Blake Mann

Reputation: 5490

Bit of a weird solution, but you could possibly fake this behaviour using absolutely positioned dashes, and overflow: hidden; on the container.

See this example:

http://jsfiddle.net/e00hgrhb/1/

I've set the h1 to be overflow: hidden; and then wrapped both items with a span element. Then this is the main styling to get it working:

h1 .item + .item {
    position: relative;
}
h1 .item + .item:before {
    content: "-";
    position: absolute;
    right: 100%;
    margin-right: 0.5em;
}

Any .item that follows another .item is set to position: relative; and it's :before pseudo-element is utilized to create the dash. I've positioned the dash using right: 100%; to make it sit entirely out of frame, to the left of the text. (I put a margin on it, as well as on every .item to allow the dash to have some space to breathe)

So what does this all do? Because the dash is absolutely positioned entirely outside of it's containing .item, it doesn't take up any space in the flow, so when the container gets too small to fit both items, the left edge of the text stays butted up against the left edge of the container. This means the dash is now also entirely outside of the h1 element.

Because the overflow of the h1 is being hidden, the dash appears to no longer be there.


Is is the best solution? I don't know... beauty is in the eye of the beholder on this one. But it is a solution, and one that doesn't require a bunch of javascript to make a relatively small change.


edit: I had to add display: inline-block; to the .item class to get this to work in firefox

Upvotes: 2

Related Questions