html - 线到中心的 CSS 过渡宽度

标签 html css css-transitions

我正在学习 CSS 过渡,我正在尝试使 3 条偏移线将宽度减小到各自的中心点。现在,宽度过渡发生在左侧而不是中心。

这是 Fiddle .

如何将每条线的宽度过渡到各自的中心点?

代码:

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>

最佳答案

使用 transform: scale() 而不是 width 并且 transform-origin 将默认为中心。

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>

关于html - 线到中心的 CSS 过渡宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43669337/

相关文章:

html - 如何用 Jade 显示多行 HTML 代码块

php - 是否可以在同一个 php 文件中包含 2 个 html 页面?

jquery - 如何定位具有 jquery 悬停效果的图像?

css - 从 svg 路径计算 css 缓动函数

android - jquery 移动或 HTML5 应用程序

javascript - jQuery .on() 点击功能不工作

html - 显示字段内容的特定图像

Jquery .hide 问题

javascript - 如何在同一页面中使用 javascript 更改 <div> 标记的可见性?

html - CSS:图像预览 - 悬停时从圆到矩形