I’m not sure if this is possible, but I thought it would be cool using CSS transforms to create an effect where a div expands from its center to a predetermined height and width, rather than just from the upper left corner.
For instance, if I have (demo)
<div id="square"></div>
and (vendor prefixes left out for brevity)
#square {
width: 10px;
height: 10px;
background: blue;
transition: width 1s, height 1s;
}
#square:hover {
width: 100px;
height: 100px;
}
On hover, this will expand the square to the right and down to 100px. I would like to have it expand from the middle.
I’m aware that I could probably use transform: scale(x) (demo), but this doesn’t really provide me with a very “pixel perfect” layout (as it is percentage-based), and it also does not affect the surrounding layout (make other elements that are in the document flow adjust to its resizing). This is essentially what I want to do, except with the document flow affected accordingly.
Does anyone know of a way to do this without javascript?
The key is to transition the margin by a formula. There is a little “wiggle” that is annoying during the transition if it is floated.
EDITED ADDING OPTIONS
Option 1: Expands within space reserved around it http://jsfiddle.net/xcWge/14/:
Option 2: Expands over elements around it http://jsfiddle.net/xcWge/18/:
Option 3: Expands over elements before it in flow and shifts elements after it http://jsfiddle.net/xcWge/22/:
ADDED NON-SQUARE EXAMPLE
A comment was made this does not work for a non-square (same width/height), but that just means one has to adjust differently for each direction during the transition. So here is Option 2 (with non-square) that starts as a rectangle, and the width expands twice as much as the height (so changes rectangle shape even) during the transition: Expands over elements around it http://jsfiddle.net/xcWge/2131/
If the
widthwere only changing by 100px also (so from 110px to 210px), then just amargin: -50pxwould have still worked.