Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the style of :before and :after pseudo-elements? [duplicate]

This is what my code looks like:

$('.mainSpan:before').css('background','url(_gfx/cmn/main_bg.png)'); 

This does not seem to work so I'm asking if it's even possible to add background images to shadow elements with jQuery.

like image 763
macksol Avatar asked Jan 09 '14 22:01

macksol


People also ask

What are before and after pseudo elements?

CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.

Can I have multiple before pseudo elements for the same element?

In CSS2. 1, an element can only have at most one of any kind of pseudo-element at any time. (This means an element can have both a :before and an :after pseudo-element — it just cannot have more than one of each kind.)

What is :: before and :: after in CSS?

The ::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.

Can we specify inline styles for pseudo elements?

You can't specify inline styles for pseudo-elements. This is because pseudo-elements, like pseudo-classes (see my answer to this other question), are defined in CSS using selectors as abstractions of the document tree that can't be expressed in HTML.


1 Answers

It's not possible to directly access pseudo-elements with Javascript as they're not part of the DOM. You can read their style using the optional second argument - which most, although not all, browsers in current use support - in .getComputedStyle() but you can't directly change their style.

However, you could change their style indirectly by adding in a new style element containing new rules. For example:

http://jsfiddle.net/sjFML/

The initial CSS assigns the :before pseudo-element with a green background, which is turned to black by inserting a new style element.

HTML:

<div id="theDiv"></div> 

CSS:

#theDiv {     height: 100px;     background: red; }  #theDiv:before {     content:' ';     display: block;     width: 50px;     height: 50px;     background: green; } 

Javascript:

var styleElem = document.head.appendChild(document.createElement("style"));  styleElem.innerHTML = "#theDiv:before {background: black;}"; 
like image 97
Ben Jackson Avatar answered Oct 12 '22 00:10

Ben Jackson