Home > Net >  Is it possible to use CSS transform property only to adjust an element's width property without
Is it possible to use CSS transform property only to adjust an element's width property without

Time:12-19

What I want to achieve is to use only transform on #b:hover to implement the very behavior of #a:hover, here is the code:

div#a, div#b {
  width:100px;
  height:30px;
  background:#ccc;
}

div#a:hover {
  width:150px;
}

div#b:hover {
  transform:scaleX(1.5);
}
<div id="a">Test1</div>

<div id="b">Test2</div>

There are now two problems:

  1. The text is stretched.
  2. The div is not expanding from the left point but from the center so it breaks out its container on its left side.

Is that possible?

CodePudding user response:

If you can consider and extra wrapper you can do it

div#a, div#b {
  width:100px;
  height:30px;
  background:#ccc;
}

div#a:hover {
  width:150px;
}

div#b:hover {
  transform: scaleX(1.5);
  transform-origin: left; /* change the origin to be left */
}

div#b:hover > div {
  transform: scaleX(calc(1/1.5)); /* the opposite transform to keep the text */
  transform-origin: inherit;
}
<div id="a">Test1</div>

<div id="b"><div>Test2</div></div>

  •  Tags:  
  • css
  • Related