Rotate Background Image of Div 90 Degrees using JQuery
Solution 1
You can add a :before to a container which contains the background (See this for more information).
.stepNode:before {
content: "";
position: absolute;
width: 200%;
height: 200%;
top: -50%;
left: -50%;
z-index: -1;
background: url(some-background-url-here) 40% 50% no-repeat;
Then you make a css class that contains the rotate properties.
.transform:before {
-webkit-transform: rotate(-30deg);
-moz-transform: rotate(-30deg);
-ms-transform: rotate(-30deg);
-o-transform: rotate(-30deg);
transform: rotate(-30deg);
}
And via jquery, you can add the class:
$(".stepNode").addClass("transform");
Also, you can set a transition time, to add animation (put this in .stepNode:before)
-webkit-transition: all 1s;
-moz-transition: all 1s;
-ms-transition: all 1s
-o-transition: all 1s;
transition: all 1s;
Here is a working jsfiddle.
Edit: 90 degrees version: jsfiddle
Solution 2
In order to achieve this, you would need to have two divs which are in absolute positioning. In containing the background image and one containing the text.
<div class="myRotate"></div>
<div class="myContent">
<p class="stepNode" aria-disabled="true">
<p class="stepLabel">
<div> New Step</div>
</p>
</p>
</div>
Next you could attach a Jquery OnClick event on whatever element you want in order for the background to rotate.
$(function(){
$('.myContent').click(function(){
$('.myRotate').css({'-webkit-transform' : 'rotate(-90deg)',
'-moz-transform' : 'rotate(-90deg)',
'-ms-transform' : 'rotate(-90deg)',
'transform' : 'rotate(-90deg)'});
});
});
Here is a working example
scientiffic
Updated on June 26, 2022Comments
-
scientiffic almost 2 years
I have a div that looks something like this:
<p class="stepNode" aria-disabled="true" style="background: url(https://...jpg) 50% 50%;"> <p class="stepLabel"> <div> New Step</div> </p> </p>
I want to rotate the background image within the div 90 degrees counterclockwise (without rotating the entire container ".stepNode". How can I do this using jQuery?
-
adeneo almost 10 yearsYou can't, as backgrounds can't be rotated
-
-
scientiffic almost 10 yearsthanks for your help. I'm trying this out, but I need to set the background of the :before element dynamically. any ideas?
-
Yatoom almost 10 yearsNormally you would select the element and use $(selector).css(). But since we are using the pseudo-element, which is not part of the DOM, we can't select it with jQuery. So, instead, you can use $("head").append() to directly add css to the html. Check the Updated jsfiddle.
-
Bondt over 9 yearsNote that this rotates the entire element.