Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep whitespace between text nodes and elements in a flex container?

Tags:

html

css

flexbox

I'm working on a feature to highlight search results on a page at runtime by wrapping text in <mark> tags. The site is using Vuetify JS so almost every element is a flex container, and (as expected) the whitespace gets collapsed between text nodes and elements in a flex container.

When I highlight part of a text node in a flex container, the spaces around the highlighted area disappear, and the element looks broken.

Example:

button {
  display: flex;
}
<button>Add to <mark>cart</mark> now</button>

<p>(Should say "Add to <mark>cart</mark> now")<p>

Is there any way to preserve the whitespace between the <mark> element and the text adjacent text nodes? Update: Since this is interacting with a Vuetify app, I'm hoping for some styles I can apply to the injected <mark> element, rather than the parent flex container.

I've tried adding pseudo-elements to the ::before/::after with content(' ') to no avail.

like image 428
DMack Avatar asked Jan 20 '26 20:01

DMack


2 Answers

Wrap it in pre tags and style it to inherit the body font

Add white-space:pre to the button rule.

Edit: p tags work too.

button {
  display: flex;
  white-space: pre;  
}
<button>Add to <mark>cart</mark> now</button>

<p>(Should say "Add to <mark>cart</mark> now")
  <p>
like image 53
Adam Avatar answered Jan 23 '26 11:01

Adam


Use non-breaking space &nbsp; instead of the two regular whitespace characters around the <mark>...</mark> tags.

button {
  display: flex;
}
<button>Add to&nbsp;<mark>cart</mark>&nbsp;now</button>

<p>(Should say "Add to <mark>cart</mark> now")<p>
like image 31
svin83 Avatar answered Jan 23 '26 10:01

svin83



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!