From b34e45f5a231b00098f6b2086d717a3eed11fcda Mon Sep 17 00:00:00 2001 From: Cassidy Williams Date: Tue, 5 Mar 2024 14:15:14 -0600 Subject: [PATCH] Add styling CSS pseudo-elements --- src/posts/styling-css-pseudo.md | 44 +++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 src/posts/styling-css-pseudo.md diff --git a/src/posts/styling-css-pseudo.md b/src/posts/styling-css-pseudo.md new file mode 100644 index 0000000..2cf5a08 --- /dev/null +++ b/src/posts/styling-css-pseudo.md @@ -0,0 +1,44 @@ +--- +layout: "../layouts/BlogPost.astro" +title: "Styling a CSS pseudo-element with JavaScript" +slug: styling-css-pseudo +description: "JavaScript can't target pseudo-elements, but that doesn't mean you can't mess with them!" +added: "Mar 05 2024" +tags: [technical] +--- + +In JavaScript, you can't do some kind of query selector like: + +```js +document.querySelector("div::after"); +``` + +But, with the power of CSS variables, you can still change the styles of those selectors with JavaScript! + +In your CSS, pick a variable name and assign it to something: + +```css +div::after { + /* 50px is the default value if --somewidth doesn't exist */ + width: var(--somewidth, 50px); +} +``` + +And in your JavaScript, you use the [`setProperty` function](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/setProperty) to assign a value to that variable! + +```js +// this is just grabbing a div, you can change it to select any element +const element = document.getElementsByTagName("div")[0]; + +element.style.setProperty("--somewidth", "50%"); +``` + +So there ya go! You can obviously make this more complex as needed. Here's an example of all of this in action! It's a template I made for tracking fundraising efforts (feel free to use the template [on CodePen](https://codepen.io/cassidoo/pen/KKYpjMJ)). +Specifically note **line 38** in the CSS, and **line 25** in the JavaScript! + +

+ See the Pen + Money goal tracker template by Cassidy (@cassidoo) + on CodePen. +

+