Is there a CSS selector for text nodes?

CssCss Selectors

Css Problem Overview


What I would like to do (not in IE obviously) is:

p:not(.list):last-child + :text {
  margin-bottom: 10px;
}

Which would give a text node a margin. (Is that even possible?) How would I get the text node with CSS?

Css Solutions


Solution 1 - Css

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

Solution 2 - Css

You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(

If you don't wrap the text node in a <span> like @Jacob suggests, you could instead give the surrounding element padding as opposed to margin:

HTML

<p id="theParagraph">The text node!</p>

CSS

p#theParagraph
{
    border: 1px solid red;
    padding-bottom: 10px;
}

Solution 3 - Css

Text nodes (not wrapped within specific tags) can now be targeted in very specific use cases using the ::target-text pseudoelement selector. A query parameter (url-encoded; e.g. whitespace must be encoded as %20) that matches a string of text can be styled like this:

::target-text { /* color, background color, etc */ }

Just like other highlight pseudoelements, only certain style properties are supported, as listed here.

There is a demo for this (parent link is on the MDN page for ::target-text). Change the query parameter string for 'text' to different strings to see how different text becomes styled.

One limitation of the ::target-text pseudoelement selector is that only the first matching string of text can be styled. In addition, at 67.8%, browser support is modest as of January 2022.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRudieView Question on Stackoverflow
Solution 1 - CssJacobView Answer on Stackoverflow
Solution 2 - CssRichard JP Le GuenView Answer on Stackoverflow
Solution 3 - CssCSSBurnerView Answer on Stackoverflow