CSS transition width of line to center

房东的猫 提交于 2019-12-12 04:38:23

问题


I am learning about CSS transitions and I'm trying to make 3 offset lines reduce width to their respective center points. Right now the width transition is occurring to the left and not the center.

Here is the Fiddle.

How can I transition the width of each line their respective center points?

The code:

const div = document.getElementById('lines')

div.addEventListener('click', function() {
	var className = div.getAttribute("class");

	if (className != 'open') {
		div.className = 'open';
	} else {
		div.className = '';
	}
})
#lines {
  width: 250px;
  height: 250px;
  position: absolute;
  cursor: pointer;
  transition: .25s ease-in-out;
}
#lines span {
  border: 1px solid black;
  display: block;
  position: absolute;
  height: 15px;
  width: 200px;
  background: #d3531a;
  border-radius: 9px;
  transition: width .25s ease-in-out;
}
#lines span:nth-child(1) {
  top: 0px;
}
#lines span:nth-child(2) {
  top: 18px;
  left: 18px;
}
#lines span:nth-child(3) {
  top: 36px;
  left: 36px;
}

#lines.open span {
  width: 16px;
}
<div id="lines">
  <span></span>
  <span></span>
  <span></span>
</div>

回答1:


Use transform: scale() instead of width and the transform-origin will be the center by default.

const div = document.getElementById('lines')

div.addEventListener('click', function() {
	var className = div.getAttribute("class");

	if (className != 'open') {
		div.className = 'open';
	} else {
		div.className = '';
	}
})
#lines {
  width: 250px;
  height: 250px;
  position: absolute;
  cursor: pointer;
  transition: .25s ease-in-out;
}
#lines span {
  border: 1px solid black;
  display: block;
  position: absolute;
  height: 15px;
  width: 200px;
  background: #d3531a;
  border-radius: 9px;
  transition: transform .25s ease-in-out;
}
#lines span:nth-child(1) {
  top: 0px;
}
#lines span:nth-child(2) {
  top: 18px;
  left: 18px;
}
#lines span:nth-child(3) {
  top: 36px;
  left: 36px;
}

#lines.open span {
  transform: scaleX(0);
}
<div id="lines">
  <span></span>
  <span></span>
  <span></span>
</div>


来源:https://stackoverflow.com/questions/43669337/css-transition-width-of-line-to-center

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!