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

Viewed 58

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.

3 Answers

If you need to preserve the white space for visual purposes, then gap: 3px is a simple way to create space between items in a flex container.

Edit: updated answer based on @herrstrietzel's suggestion to use 0.2em instead of pixels, so the spacing scales with font size increase (Codepen demonstration in comments).

button {
  display: flex;
  gap: 0.2em;

}
<button>Add to <mark>cart</mark> now</button>

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

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>

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>

Related