How to show the width of an element in the content of an ‘:after’ pseudo-element?

I’m looking to show the width of an element within a pseudo element.

so my CSS would look like

:after {
  content: "{width goes here}";
  display:block;
}

but I have no idea if its even possible with just CSS.

If not, how would I do it with jQuery?


solution

It’s currently not possible to do this with CSS alone.

You could use JavaScript to iterate over the elements and set a custom data-width attribute based on the computed width of the element. In doing so, you can use the content value of attr(data-width) in order to display this attribute value as the pseudo element’s content. The CSS attr() function allows you to retrieve the element’s attribute and display the value.

For instance:

var elements = document.querySelectorAll('[data-width]');
for (var i = 0; i < elements.length; i++) {
  elements[i].dataset.width = elements[i].offsetWidth;
}
[data-width]:after {
  content: ' ' attr(data-width) 'px';
}
[data-width] {
  border: 1px solid;
}
div {
  width: 300px;
  height: 30px;
}
<div data-width></div>
<p data-width>Paragraph element</p>
<span data-width>Span</span>

Since the data-width attribute is only set once, you would need to add a resize event listener in order to set the corresponding width values when they change.

For instance:

window.addEventListener('resize', setDataWidth, true);
setDataWidth();

function setDataWidth() {
  var elements = document.querySelectorAll('[data-width]');
  for (var i = 0; i < elements.length; i++) {
    elements[i].dataset.width = elements[i].offsetWidth;
  }
}
[data-width]:after {
  content: ' ' attr(data-width)'px';
}
[data-width] {
  border: 1px solid;
}
div {
  width: 30%;
  height: 30px;
}
<div data-width></div>
<p data-width>Paragraph element</p>
<span data-width>Span</span>