如何为App组件中currency容器内的按钮设置不同颜色?
问题描述
我有一个简单的App组件:
function App() { const [base,setBase] = useState("") const [code,setCode] = useState("") return ( <div className="currency"> ... <button className="btn" type="button">Get</button> </div> ); }
尝试用CSS为按钮设置颜色:
.App { text-align: center; } .currency { background-color: aqua; position: absolute; top:0px; right:0px; bottom:0px; left:0px; } .btn{ position: absolute; width: 100px; height: 50px; top: 10%; margin: 400px 0 0 350px; padding: 16px 42px; box-shadow: 0px 0px 12px -2px rgba(67, 65, 73, 0.5); line-height: 1.25; text-decoration: none; font-size: 16px; text-transform: uppercase; overflow: hidden; background-color: blue; color: #000; }
但无论怎么设置,按钮都无法显示指定颜色,始终呈现currency容器的颜色。即使把按钮单独放入div中问题依旧,且无法将按钮移出currency容器,请问该如何为按钮设置独立颜色?
解决方案
问题根源在于按钮样式的冲突以及未处理浏览器默认按钮样式,调整方案如下:
- 添加
box-sizing: border-box,让padding包含在设置的宽高范围内,避免内容溢出被隐藏; - 移除
overflow: hidden(或保留但确保内部内容不超出); - 移除浏览器默认的按钮边框,添加
border: none;
修改后的.btn样式:
.btn{ position: absolute; width: 100px; height: 50px; top: 10%; margin: 400px 0 0 350px; padding: 16px 42px; box-sizing: border-box; box-shadow: 0px 0px 12px -2px rgba(67, 65, 73, 0.5); line-height: 1.25; font-size: 16px; text-transform: uppercase; background-color: blue; color: #000; border: none; cursor: pointer; }
如果不想固定宽高,也可以直接去掉width和height,让按钮根据padding自适应大小,这样更稳妥:
.btn{ position: absolute; top: 10%; margin: 400px 0 0 350px; padding: 16px 42px; box-shadow: 0px 0px 12px -2px rgba(67, 65, 73, 0.5); line-height: 1.25; font-size: 16px; text-transform: uppercase; background-color: blue; color: #000; border: none; cursor: pointer; }
调整后按钮就能正常显示指定的蓝色背景,不会继承父容器的颜色。
内容的提问来源于stack exchange,提问作者Alpharius
相关产品推荐
相关产品推荐

