What is the best way to link HTML transformations across several classes?

Is it possible to combine multiple transforms in a single element to create a unique end result?

It seems that when applying multiple transform properties to an element, only one of them will be recognized.

For example, trying to transform a div with both rotate(20deg) and skewY(20deg) like this:

.foo {
  transform: rotate(20deg);
}

.bar {
  transform: skewY(20deg);
}
<div class="foo bar"></div>

Only one transformation will take effect. While combining the transformations manually could work, it's not practical due to the countless potential combinations. Instead, how about doing something like this:

.one {transform: rotate(10deg);}
.two {transform: rotate(20deg);}
.three {transform: rotate(30deg);}
.four {transform: rotate(40deg);}

.uno {transform: skewY(10deg);}
.dos {transform: skewY(20deg);}
.tres {transform: skewY(30deg);}

I am exploring various solutions such as:

  • Finding a way to add to the existing transform property of a <div>
  • Potentially modifying classes dynamically
  • Utilizing jQuery to change CSS without overwriting existing properties

While I prefer CSS/JavaScript solutions, any input using jQuery is also welcome!

Answer №1

If you want to utilize CSS custom properties (var(--X)), you can set all transformations to default values of 0 and then update them using className. Check out the following links for more information on CSS custom properties:

You can experiment with this concept without JavaScript in this example: CodePen Example

.foo {
  --rotate: 20deg;
}

.bar {
  --skewY: 20deg;
}

div[class] {
  transform: rotate( var(--rotate, 0)) skewY( var(--skewY, 0));/* fallback value is here 0 */
}


/* demo purpose */

div[class] {
  float: left;
  border: solid;
}

html {
  display: flex;
  height: 100%;
}

body {
  margin: auto;
}
<div class="foo bar">foo bar</div>
<div class="foo ">foo</div>
<div class="bar">bar</div>
<div class="nop">no transform</div>

For further details on CSS custom properties, visit: MDN Web Docs

Custom properties prefixed with '--' hold values that can be used in other declarations with the 'var()' function.

Keep in mind that custom properties are scoped to their declared elements and take part in cascading.

Learn how to handle fallbacks using custom properties:CSS Variables Fallback Example

Note: Fallback values for custom properties can include commas for multiple fallback options.

If you have issues with browser support, check out this article: IE11 Polyfill for CSS Variables Support

Answer №2

There are numerous approaches you can take to tackle this issue. How about considering the following method? I've implemented two ` to extract the skew and rotation values and then apply the corresponding effects.

Keep in mind that it doesn't matter where the values originate from. They could be hardcoded in your buttons as data-* attributes (if you prefer them fixed). The purpose is to demonstrate how you can handle it with JavaScript (I have included some comments to simplify understanding):

var object = document.querySelector(".shape");

// This function manages the Rotational effect
function rotate(event)
{
  var rotation_val = document.getElementById("rotationVal").value;
  
  // Retrieves the CSS transform expression for rotation, stored as a data-attribute on each button to indicate its responsible transformation. However, you can store this information anywhere you prefer.
  var css_transform = event.currentTarget.getAttribute("data-rotation");
  
  // Replaces, for example, rotate(_r_) with rotate(15deg) if the value was 15
  var effect = css_transform.replace("_r_", rotation_val + "deg");
  
  // Note here that I am not replacing the transform property. Instead,
  // I am adding a new transformation to it, essentially compounding dynamically.
  object.style.transform += effect;
}

// This function handles the Skewing effect
function skewY(event)
{
  var skew_val = document.getElementById("skewVal").value;
  var css_transform = event.currentTarget.getAttribute("data-skew");
  var effect = css_transform.replace("_s_", skew_val + "deg");
  object.style.transform += effect;
}

function apply_all()
{
  var buttons = document.querySelectorAll(".effect_button");
  
  buttons.forEach(function(button){
    button.click();
  });
}
.container{
  padding: 60px;
  border: thin solid #dbdbdb;
}

.shape{
  width: 60px;
  height: 60px;
  background-color: green;
}
<div class="container">
  <div class="shape">
  </div>
</div>

<input id="rotationVal" />
<button class="effect_button" data-rotation="rotate(_r_)" onClick="rotate(event)">rotate</button>
<br />
<input id="skewVal" />
<button class="effect_button" data-skew="skewY(_s_)" onClick="skewY(event)">Skew</button>
<br />

Or Rotate and Skew at the same time:
<button onClick="apply_all(event)">Transform</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble arises when rendering nested components in React Router 4

My issue lies with implementing React Router 4 while utilizing "nested" routes. The problem arises when one of the top routes renders a component that matches the route, even though I do not want it to be rendered. Let me provide the relevant code snippets ...

Alert from Google Chrome about Service Worker

My situation involves using FCM for sending web notifications. However, I am encountering a warning and the notifications are not functioning as expected when clicked (i.e., opening the notification URL). Below is my Service-Worker code: importScripts(& ...

Tips for accessing a unique window name in JavaScript

How can I make window.name persist between page refreshes? I need to use window.name to differentiate between multiple browser windows, allowing each one to display distinct data while sharing the same URL. However, my problem is that the value of window ...

Is there a way to streamline this query code that seems overly complex?

Could someone please assist me in simplifying this code? I am trying to shorten or simplify the query code by using a stored procedure, but I still need to include the details inside the "()" parentheses. I am new to Node.js and would appreciate any help. ...

In Typescript, it is not possible to assign the type 'any' to a string, but I am attempting to assign a value that is

I'm new to TypeScript and currently learning about how types function in this language. Additionally, I'm utilizing MaterialUI for this particular project. The issue I'm encountering involves attempting to assign an any value to a variable ...

Customize the appearance of each element in ng-repeat individually

In my code, I have implemented an ng-repeat. Each alternate div inside the ng-repeat is supposed to have a different border-color, which is achieved by using the following structure: <div ng-repeat="channel in channelList"> <div ng-style="get ...

Creating a Basic JQuery Dialog Box

Issue with jQuery Trigger <script type="text/javascript" src="simpledialog.js"></script> <link href="simpledialog.css" type="text/css" rel="stylesheet" /> <script type="text/javascript"> $(document).ready(function () { $('.s ...

Issue with incremental static generation in version 13 not functioning as expected

Is ISR working for anyone in the NextJS 13 Beta version? I have set revalidate to 15 as follows. export const revalidate = 15; However, even after running `npm run build`, the page still remains a statically generated site (SSG). The symbol is showing u ...

I encountered a sudden halt in functionality with my NextJs useState feature

'use client' import React, { useState } from 'react'; import Image from 'next/image'; export default function Home() { const [count,setCount] = useState<number>(0) const add = ()=> { setCount(prevCount => ...

Is it possible to set data using a React Hooks' setter before the component is rendered?

Instead of making a real API call, I am exporting a JS object named Products to this file to use as mock data during the development and testing phase. My goal is to assign the state of the function to this object, but modified with mapping. The current st ...

Unlock the innerHTML of a DIV by clicking a button with ng-click in Angular JS

I am curious about something. There is a <div> and a <button> in my code. I am looking to access the inner markup of the <div> within the ng-click function without relying on jQuery. Can you give me some guidance? <div id = text-entry ...

Warning: HTML input values are being cleared when added

I've been working on some code that adds an input field when a button is clicked. When the limit reaches 5 (counter), it displays a bootstrap warning. The issue I'm facing is that after hitting "add field" more than 5 times, the values in the fie ...

The Art of Capturing Sound: Unleashing

Currently, I am attempting to capture video via html5 .getUserMedia and play it back without needing to upload it to a server. Despite following numerous tutorials, I have only been successful on Chrome by utilizing canvas to draw the webp image and then c ...

Image not showing up when using drawImage() from canvas rendering context 2D

Need help with drawImage() method in JavaScript <head> </head> <body> <script type = "text/javascript"> var body, canvas, img, cxt; body = document.getElementsByTagName("body" ...

Choosing solely the following immediate sibling

After researching various solutions on different platforms for selecting the next sibling, I always encounter some kind of issue when implementing the suggested code. Here is the current structure I have: <div class="article" id="onea"> &l ...

Creating a new component when a click event occurs in React

Currently diving into the world of React while working on a project that involves mapbox-gl. I'm facing an issue where I can successfully log the coordinates and description to the console upon hover, but I can't seem to get the popup to display ...

Changing the href of an image when the slide changes: Tips and tricks

Currently, I am utilizing the slick slider slideshow and facing an issue with updating the href of a logo image as the slides progress. Despite trying out two different scripts, none of them have proven to be effective. <main class="Site-content"> & ...

Issue with exchanging columns in Bootstrap version 5.0

Seeking assistance! I am a beginner with bootstrap and struggling to figure out an issue I'm experiencing. In the attached image(s), my goal is to have the coin image positioned above its corresponding text on the left side when the screen size is red ...

Rerender not occurring after array splice with React hooks setter

My parent component structure is as follows: import React from "react"; import Test from "./Test"; function App() { const [configs, setConfigs] = React.useState([1, 2, 3]) return ( <div> ...

What is the best way to enable the user to scroll smoothly while new data is continually being added to the screen?

I'm attempting to develop a chat feature where the scroll automatically moves down when new messages are received by the user. However, I've come across an issue while trying to allow users to manually scroll up. Every time I scroll up and a new ...