Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css transform without overwriting previous transform?

Tags:

I have an element:

elem    transform translateY(5px) scale(1.2)  

Now on hover I want it to move down an additional 5px

elem:hover    transform translateY(5px) 

Obviously this would overwrite the previous transform. Is there anyway to set it to move an additional 5 without knowing what the previous transform state is?

Thanks.

like image 784
Harry Avatar asked May 04 '11 23:05

Harry


People also ask

Can you have multiple transforms CSS?

The transform property can be given multiple values that are applied one after another. It applies the rightmost value and then the ones on the left, which means that the value which is last in the list would be applied first.

What is the difference between transform and transition in CSS?

So, what's the difference between CSS Transform and CSS Transition? The Transform property in CSS moves or modifies the appearance of an element, whereas the Transition property seamlessly and gently transitions the element from one state to another.

What is CSS WebKit transform?

The -webkit-transform-2d Boolean CSS media feature is a WebKit extension whose value is true if vendor-prefixed CSS 2D transform s and non-standard vendor-prefixed media queries are supported. Apple has a description in Safari CSS Reference.

How does transform work in CSS?

The transform CSS property lets you rotate, scale, skew, or translate an element. It modifies the coordinate space of the CSS visual formatting model.


2 Answers

CSS custom properties aka CSS variables are the only answer to this (outside of using Javascript).

To add to a previous value:

div {   --translateX: 140;   --trans: calc(var(--translateX) * 1px);   transform: translateX(var(--trans)) scale(1.5); }  div:hover {     --translatemore: calc(var(--translateX) + 25);  --trans: calc(var(--translatemore) * 1px); }  div {   transition: .2s transform;   width: 50px;   height: 50px;   background: salmon; } 

Eventually all browsers will support the ability to set transform properties individually.

  • https://caniuse.com/mdn-css_properties_translate
  • https://caniuse.com/mdn-css_properties_scale
like image 90
Ollie Williams Avatar answered Oct 04 '22 02:10

Ollie Williams


Use the WebKitCSSMatrix object or MozCSSMatrix (I think...) to set new values trough the original object without knowing the initial transform.

http://jsfiddle.net/Cx9hH/

In this case I have an initial translate of 100px on witch I add an extra 100px:

box.style.webkitTransform = matrix.translate(100, 0); 
like image 26
Mircea Avatar answered Oct 04 '22 03:10

Mircea