Using CSS attr() with styled components

Viewed 2591

I'm trying to put a percentage figure inside an svg circle using the css content attr function, like so:

content: attr(data-percent)%;

The pseudo element won't render because Styled components doesn't seem to be able to handle the % at the end. If I remove it it works, but I want the number to display as 20% and this format is valid for regular CSS.

Is there something I'm missing here or is it a limitation with the library?

const Div = styled.div`
  position: relative;
  width: 100%;
  height: 100%;
  &:after {
    content: attr(data-percent)%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
`;

render() {
    return (
      <Div data-percent={20}>
        <sgv viewBox="0 0 120 120">
          <circle cx="60" cy="60" r="50" fill="none" strokeWidth="10" strokeLinecap="round"/>
        </svg>
      </Div>
    );
  }
1 Answers

The percent sign needs to be a string and separated from the attr() value like so:

content: attr(data-percent) "%";

Or just put the percent sign into the data attribute instead of the css style

data-percent="20%"

Demo

div {
  position: relative;
  width: 100%;
  height: 100%;
}

div:after {
  content: attr(data-percent) "%";
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
<div data-percent="20">
  <svg viewBox="0 0 120 120">
    <circle cx="60" cy="60" r="50" fill="none" strokeWidth="10" strokeLinecap="round" />
    </svg>
</div>

Related