You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML和CSS中随按钮文字缩小同步缩小按钮尺寸?

问题解决与代码优化

核心问题解决

你之前修改宽高导致按钮向角落收缩,是因为元素尺寸变化时默认从左上角调整位置。用transform: scale()是最简便的居中收缩方案,它会基于元素中心进行缩放,完全符合你要的效果。

优化后的完整代码

HTML

<button>点击按钮</button>

CSS

button {
  font-size: 10px;
  font-family: 'Roboto', Arial, sans-serif;
  color: #fff;
  background-color: rgb(59, 102, 241);
  border: none; /* 替代border-width: 0px,写法更简洁 */
  border-radius: 100px;
  width: 190px;
  height: 25px;
  transition: transform 0.3s, background-color 0.3s; /* 明确过渡属性,替代all,提升性能 */
}

button:hover {
  background-color: rgb(87, 125, 250);
  cursor: pointer;
}

button:active {
  transform: scale(0.95); /* 缩放至原尺寸的95%,实现居中收缩 */
  /* 移除原有的font-size和padding修改,避免布局偏移 */
}

额外优化说明

  • 将border-width: 0px替换为border: none,写法更简洁规范
  • 为字体列表添加sans-serif兜底,避免Roboto字体加载失败时显示异常
  • 把过渡属性从all改为具体的transform和background-color,减少不必要的过渡计算,提升页面性能
  • 移除caret-color: transparent,按钮默认不会出现输入光标,该属性在此处无作用

内容的提问来源于stack exchange,提问作者ניין

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 12:42:04