Home > OS >  How can I strip substrings from retrieved data attribute values with CSS?
How can I strip substrings from retrieved data attribute values with CSS?

Time:09-27

I’m using attr() CSS function to retrieve the values of attributes of an element:

HTML:

<div 
     data-name="name@Classification"
     data-content="content@Public" />

  CSS:

div.othermeta:after {
    content: attr(data-name) ": " attr(data-content);
}

The result is as expected:

name@Classification: content@Public

Now I would like to strip out "name@" and "content@" from the retrieved attribute values so that the result looks like this instead:

Classification: Public

Does anyone have an idea of how to do this without JavaScript?

div.othermeta:after {
    content: attr(data-name) ": " attr(data-content);
}
<div 
     data-name="name@Classification"
     data-content="content@Public" />

CodePudding user response:

CSS isn't a scripting language. While it does have a few function-like features, it doesn't do string parsing.

You could bang things into shape by using both of the available pseudo-elements, but it's extremely fragile. Any change in font size, font family, etc. breaks it.

.othermeta {
  position: relative;
  overflow: hidden;
}

.othermeta:before,
.othermeta:after {
  position: absolute;
  background: #fff; /* critical for masking */
}

/* note reverse order for proper layering */
.othermeta:after {
  content: attr(data-name) ": ";
  transform: translateX(-53px);
  padding-right: .5rem; /* word spacing */
}

.othermeta:before {
  content: attr(data-content);
  transform: translateX(40px);
}

/* override for different name attribute value */
.othermeta[data-name^="name@Other"]:before {
  transform: translateX(76px);
}
<div  data-name="name@Classification" data-content="content@Public">
  &nbsp;
</div>

<div  data-name="name@OtherClassification" data-content="content@Private">
  &nbsp;
</div>

  • Related