Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transition pixel to percent

I would like do a transition using CSS, but my element's dimensions are in pixels normally but in percent during the :hover event, and the transition doesn't work like this. Do you know any way to do this?

like image 320
Guillaume Avatar asked Nov 28 '22 17:11

Guillaume


2 Answers

You can apply the transition on the % width and just use min-width as px fixed value.

.elem {
    min-width:50px; /* min-width as the pixel value */ 
    width:0%; /* width as the % value */ 
    transition:width .8s ease; /* transition applied to width */
}
.apply-new-width {
    width:100% !important;
}

Be carefull min-width is stronger than width. So when you'll apply the new width (in %) min-width will still override it. You have several options to handle this : increase the .apply-new-width specificity (eg: .elem.apply-new-width or div.apply-new-width) or use the !important rule. Usually !important is a bad solution but here it does the trick.

Here's a jsfiddle of a working exemple. It works in all browsers, except of course in IE where transitions are not supported, but it gracefully degrades so we can say it works every where :)

Cheers

like image 193
Julien Knebel Avatar answered Dec 12 '22 07:12

Julien Knebel


It works just fine - http://jsfiddle.net/eCxQP/

Normal width - in pixels, hover - in percent

body {
     width: 100%;
 }


 div  {
     width:100px;
     height:100px;
     background:red;
     transition:width 2s;
     -moz-transition:width 2s; /* Firefox 4 */
     -webkit-transition:width 2s; /* Safari and Chrome */
     -o-transition:width 2s; /* Opera */
 }

 div:hover {
     width:33%;
 }

UPDATE: works in FF, not the Webkit based browsers

like image 40
Zoltan Toth Avatar answered Dec 12 '22 07:12

Zoltan Toth