Width auto jquery animation

I have a <span id="example">Some random text</span>. It’s width and opacity has been set to 0px/0 respectively. Upon clicking invoking button, I would like to animate this span, to achieve it’s natural size which I don’t know since it’s generated by browser.

$("span#example").animate({"width": "auto"});

Is what I’m talking about. The span has no fixated or predictable width and will change however they want to interpret it. All I want is to animate it from width: 0px to it’s unpredictable rendered size.

You can’t change the width of inline elements such as span - their width is determined by their content.

	padding: 7px 0 7px 0;
	background-repeat: no-repeat;
	background-size: contain;
	text-decoration: none;
	color: #FFF;
	overflow: hidden;
	display: inline-block;
	width: 0px;

Apparently you can.

No you can’t :smile:

You can’t apply dimensions to inline elements but you can change their display values from inline to inline-block (or to block or to one of the other block display values) and then you can apply dimensions to them. Of course changing the display value will affect how the element behaves but using ‘inline-block’ should not cause undue problems to inline fragments.

What Felgall said is technically correct :smile:

Are you confusing width with max-width?

No. Why would it be max-width?

Like you’ve found transitioning from 0 to ‘auto’ doesn’t work, animating max-height / max-width is the trick you are looking for.

div {
  max-width: 0;
  max-height: 0;
  overflow: none;
  transition: 1s;
div:hover {
   max-width: 1400px; // larger than expected
   max-height: 500px; // larger than expected

I stand corrected.

I had believed that width 0 would be expanded to fit content but that max-width 0 wouldn’t.

But testing just now proves this to not be the case.

YES!! Exactly! Thank you!

No problemo.

Once you apply that the element is no longer an inline element.

I hate nitpicking since you answered the question Mark but that’s a new one on me :smile:

and so are these :smile:

I figured it was meant to be “hidden”.
(I still get display and visibility values mixed up sometimes)

But then

Now I’m thinking I’m not testing in the right browsers.

Yes, that’s what I assumed and is an easy mistake:)

The code as it stands will need some work (hiding overflow, and providing a trigger point to hover) but max-width (or height) will allow a transition from zero to content width (on shrink to fit elements) but the animation is always a bit jumpy. I mentioned the trick here a few years ago,

I’ve spent too long in JavaScript :smile:

Those single line comments sure would be handy though.

[Insert Sass plug here]

1 Like

Sounds painful :anguished:

1 Like

I’m guessing you’re not a masochist?

(Let me be clear; I don’t recommend Sass for every working situation)

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.