I need the height of a pseudo :before
element. Sounds like a no-brainer, but I cannot get it to work. This is what I have tried:
$('.test:before').height() // --> null
And a jsfiddle Any suggestions what I do wrong ?
UPDATE: The height of .test
depends on the content. What I need to do is, when the height gets bigger than the pseudo element, I need to add a padding to the right of the element. However, because the height of the pseudo element is set by css I don't know it in my program
::before. In CSS, ::before creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
Definition and UsageThe ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content. Version: CSS2.
The height property sets or returns the height of an element. The height property has effect only on block-level elements or on elements with absolute or fixed position. The overflowing content can be manipulated with the overflow property. Tip: Use the width property to set or return the width of an element.
A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element(s). For example, ::first-line can be used to change the font of the first line of a paragraph.
Super-late reply, but: you can use vanilla JavaScript to get pseudo-element dimensions using the getComputedStyle
method:
var testBox = document.querySelector('.test');
// Or with jQuery: testBox = $('.test').get(0); - We want the JS element, without the jQuery wrapper
var pseudoBeforeHeight = window.getComputedStyle(testBox, ':before').height; // Returns (string) "70px"
This will return a string of the pixel value, regardless of the CSS declaration (e.g. 4.375rem = 70px
, 10vh = 70px
, calc(8vh + 1rem) = 70px
, so to get the number (in pixels) you can just do:
var pseudoHeightNum = parseInt(pseudoBeforeHeight);
With regards to compatibility: CanIUse suggests that, as of July 2017 it works pretty much across the in all modern browsers (apparently even with support for IE9 and above): reference.
As Paulie_D said, "Pseudo elements are not selectable by jQuery".
However, if the elements on your site are styled in the same way as they are in the JSFiddle, then the div will end up being the same height as the :before, which you CAN get the value of:
$('.test').height()
If it isn't the same, then let us know why you wish to get the height, and there may be something else you can do.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With