按钮悬停时‘Add Product’文本不显示,求非body:flex解决方案
问题分析与解决方案
首先咱们先揪出代码里的两个关键问题,这就是导致hover时“Add Product”不显示的根源:
- 选择器语法错误:你写的
.button:span是错误写法,要选中按钮内的span元素,应该用.button span(冒号是伪类的专属语法,比如:hover,这里是子元素选择器,不需要冒号)。 - 按钮布局属性缺失:
.button设置了display: inline,行内元素没法作为绝对定位子元素的定位容器;而且你没给按钮加position: relative,导致内部的绝对定位span是相对于body来定位的,自然没法在按钮内部显示。
不用给body加display: flex,咱们只需要调整按钮的几个属性就能解决问题,具体方案如下:
修改后的完整代码
CSS部分
.button { background: #f6bc00 no-repeat -12px center; border: 1px solid #f6bc00; border-radius: 4px; color: #fff; display: inline-block; /* 把inline改成inline-block */ position: relative; /* 添加相对定位,作为内部绝对定位元素的基准 */ font-size: 9px; font-weight: 700; overflow: hidden; padding: 5px 8px 3px 8px; text-decoration: none; line-height: 8px; text-transform: uppercase; transition: padding .2s ease, background-position .2s ease, transform .5s ease; } .button span { /* 修正选择器 */ margin: 0; padding: 0; } .button:hover { transform: scale(1, 1); padding-left: 88px; padding-right: 5px; background-position: 5px center; } .button span:nth-child(1) { position: absolute; left: -70px; transition: left .2s ease; } .button:hover span:nth-child(1) { bottom: 3px; left: 20px; } /* PRESENTATION */ body { background-color: black; } .button:nth-child(1) { margin-right: 1em; }
HTML部分(无需修改)
<a class="button" href="#" download=""> <span>Add Product</span> <span>Add</span></a>
方案解释
display: inline-block:既保留了行内元素可以和其他元素在同一行排列的特性,又拥有块级元素的布局能力,能正确包裹内部的绝对定位元素,避免布局错乱。position: relative:给内部的绝对定位span提供了定位参考,让span的left、bottom属性都是相对于按钮本身计算,hover时就能准确移动到按钮内部显示出来。- 修正选择器:确保span的样式能正确生效,不会因为选择器错误导致样式失效。
这样调整后,你不用修改body的display属性,hover时“Add Product”就能正常显示啦!
内容的提问来源于stack exchange,提问作者GustyMouse




