Quasipickle
Quasipickle

Reputation: 4498

How to place elements on top of each other

I have a <button> with 3 spans in it - each span containing different text. At different times, triggered by Javascript, the class of the button will change. Using CSS transitions & transform, I have one span moving out of the button, and another moving in. That all works.

The problem is that the button has grown to the full width of span 1 + span 2 + span 3. I want the width to be simply large enough to contain the largest of the spans. If all the spans could be placed one on top of the other, this would work.

I can't figure out how to get the 3 spans to sit one on top of the other.

Here's a fiddle showing the problem: http://jsfiddle.net/V9yTs/ (Click the button to see the change)

Edit Here's the final, working fiddle: http://jsfiddle.net/XW3DY/7/

Upvotes: 1

Views: 2130

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

Since you already use jQuery, you can just calculate the proper width and height

var w = 0;
$('.btn .msg').each(function () {
    w = Math.max(w, $(this).width());
});

$('.btn').width(w);

var h = 0;
$('.btn .msg').each(function () {
    h = Math.max(h, $(this).height());
});

$('.btn').height(h);

But now the .msg spans are arranged vertically. To compensate for that, depends on what you what to achieve. One solution is to use position: absolute

.btn {
    position: relative;
}
.btn-status .msg {
    position: absolute;
}

The .msg spans are now lying on top of each other. You must also adjust the vertical transformation.

See modified JSFiddle

Upvotes: 0

NathanW
NathanW

Reputation: 301

A solution for layering your spans on top of each other would be to use position: relative; (which I see you already have there) and then modify the top margin of spans 2 and 3 so that they move up to the same position as the span 1.

Here's an updated version of your JSFiddle: http://jsfiddle.net/XW3DY/2/

(Please note that floated elements cannot be placed on top of each other. This is why relative positioning is generally used for placing elements of top of one another.)

Upvotes: 2

Related Questions