CSS实现:如何让div宽度变化方向向左而非向右?
实现左侧div反向宽度变化的方法
你原来的代码
CSS
table { width: 200px; height: 100px; } .arrow { border-radius: 1rem; width: 100%; height: 100%; background-color: black; transition: 200ms; } .arrow:hover { border-radius: 1.2rem; width: 120%; height: 120%; } .arrow:active { border-radius: 0.9rem; width: 90%; height: 90%; }
HTML
<table> <tr> <td><div class="arrow"></div></td> <td><div class="arrow"></div></td> </tr> </table>
两种实现反向效果的方法
方法一:位置偏移法
给左侧箭头加个arrow-left类,通过调整相对位置,让宽度增加时向左扩展:
修改后的CSS
table { width: 200px; height: 100px; } .arrow { border-radius: 1rem; width: 100%; height: 100%; background-color: black; transition: 200ms; } .arrow:hover { border-radius: 1.2rem; width: 120%; height: 120%; } .arrow:active { border-radius: 0.9rem; width: 90%; height: 90%; } /* 左侧箭头反向效果 */ .arrow-left:hover { position: relative; left: -10%; /* 向左偏移宽度增量的一半,实现向左扩展 */ top: -10%; /* 同步上移,保持垂直居中 */ } .arrow-left:active { position: relative; left: 5%; /* 向右偏移宽度减少量的一半,维持居中 */ top: 5%; }
修改后的HTML
<table> <tr> <td><div class="arrow arrow-left"></div></td> <td><div class="arrow"></div></td> </tr> </table>
方法二:transform缩放法(更流畅)
用transform缩放配合变换原点,性能更好,过渡更丝滑,不会影响布局:
修改后的CSS
table { width: 200px; height: 100px; } .arrow { border-radius: 1rem; width: 100%; height: 100%; background-color: black; transition: all 200ms; /* 确保所有属性都有过渡 */ } .arrow:hover { border-radius: 1.2rem; transform: scale(1.2); /* 整体缩放1.2倍 */ } .arrow:active { border-radius: 0.9rem; transform: scale(0.9); /* 缩放到0.9倍 */ } /* 左侧箭头设置变换原点为左侧,缩放时向左扩展 */ .arrow-left { transform-origin: left center; } /* 右侧箭头可以设置变换原点为右侧,让它向右扩展(和你原来的效果一致) */ .arrow-right { transform-origin: right center; }
修改后的HTML
<table> <tr> <td><div class="arrow arrow-left"></div></td> <td><div class="arrow arrow-right"></div></td> </tr> </table>
内容的提问来源于stack exchange,提问作者Sacha Jubinville
相关产品推荐
相关产品推荐

