Home > Mobile >  Apply CSS styling to text content either before or after a specific element
Apply CSS styling to text content either before or after a specific element

Time:10-07

Given the following HTML markup:

<li class="lrn-text-word-wrap" tabindex="-1" data-selector="suggested-tag">
  12345: <strong>Han</strong> Solo
</li>

Is it possible to apply styling with only css to remove the 12345: text content?

I do not have control over the markup so cannot make changes there and really don't want to have to resort to JS.

What I'm trying to achieve here is to use CSS to only show the words "Han Solo" rather that "12345: Han Solo"

The reason the <strong> tag only wraps "Han" is this is part of an autocomplete and the user has types "Hans" The markup shows a matching result, highlighting the text the user typed, which is fine, but I need to be able top hide the "key" part.

I have put together the following SCSS, but this only allows the <strong> text to remain whereas we need to also show everything after the <strong> too.

[data-selector='suggested-tag'] {
  font-size: 0px
  strong {
    font-size: 12px;
  }
}

Alternatively, if there is a way to select just text nodes via CSS this would probably be sufficient.

Any suggestions to how to approach this would be greatly received!

CodePudding user response:

You could give a try with a grid-layout and set the first column to 0 and a background to the strong element to hide what overflows from that first column.


Explanation: grid will wrap every portion of text inside a virtual cell. If html tags are standing among the text it will produce as many portions.

Your example will produce 3 cells , 1 virtual for the text standing ahead the <strong> tag , the second element will be the <strong> tag itself and the third(virtual) will be the text standing after that <strong> tag.


here is the idea:

ul,
li {
  margin: 0;
  padding: 0;
  list-style:none;
}

li.grid {
  display: grid;
  grid-template-columns: 0 repeat(2, minmax(3em, max-content));
  justify-content: start;
  background: lightgray;
}

.grid strong {
  background: inherit;
  padding:0 0.2em;
  text-align: right
}
<ul>
  <li class="grid"> 12345: <strong>Han</strong> Solo</li>
  <li> 12345: <strong>Han</strong> Solo</li>
</ul>

  • Related