问题
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?
回答1:
You may have to use JavaScript to change the percentage value to pixels after it has been calculated. I think webkit reports dimensions in px regardless of how they were set when called via JavaScript.
回答2:
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
回答3:
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
回答4:
I works fine on Firefox but not on Chromium for which you need to use the same unit.
回答5:
I know this is very old but if your support is IE9 and above you can do something like this...
In Css
div{ width:100%; transition: width .2s ease;}
div.set-px-width { width: calc(0% + 50px); }
In JS
div.className += "set-px-width"
The above would transition from 100% width to 50px width by using the calc with a percent of 0. This seems to still treat the width as percent and will transition appropriately
来源:https://stackoverflow.com/questions/8975538/transition-pixel-to-percent