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

Time:09-08

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?

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

CodePudding user response:

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.

button {
  display: flex;
  gap: 3px;

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

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

CodePudding user response:

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>

CodePudding user response:

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