如何在Input文本框内放置Copy to Clipboard图标?
解决密码生成器中复制图标嵌入输入框的定位问题
要把复制图标放到输入框内部,核心是利用相对定位+绝对定位的组合来实现,而非单纯用flex布局推挤。以下是具体调整方案:
关键修改思路
- 将包含输入框和图标的容器设置为
position: relative,作为绝对定位的参考基准 - 给输入框添加右侧内边距,预留图标的位置,避免输入的密码文本被图标遮挡
- 对复制图标设置
position: absolute,直接定位到输入框的右侧内部区域
修改后的完整代码
CSS 部分
body{ margin: 0; } #container{ background-color: #1F2937 ; width: 650px; height: 475px; margin: 0 auto; margin-top: 100px; border-radius: 12px; } #main-flex-container{ display: flex; flex-direction: column; align-items: center; } h1 { margin-left: -40px; padding-top: 30px; font-size: 48px; font-family: Karla; font-weight: 700; color: #ffffff; } span{ color: #4ADF86; } h2{ margin-top: -20px; margin-bottom: 40px; font-size: 24px; color: #ffffff; font-family: Inter; font-weight: 400; } #input-flex-container{ display: flex; justify-content: center; /* 新增:设为相对定位,作为图标绝对定位的基准 */ position: relative; } input { width: 440px; height: 35px; border: none; border-radius: 6px; /* 新增:右侧内边距,避免文本被图标遮挡 */ padding-right: 40px; box-sizing: border-box; /* 确保内边距不会撑大输入框宽度 */ } input:focus{ outline: none; } /* 新增:复制图标的定位样式 */ #input-flex-container img{ position: absolute; right: 10px; /* 距离输入框右侧的距离 */ top: 50%; transform: translateY(-50%); /* 垂直居中 */ width: 20px; /* 根据你的图标尺寸调整 */ height: 20px; cursor: pointer; /* 鼠标悬停显示手型,提升交互感 */ }
HTML 部分
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Karla:ital,wght@0,200..800;1,200..800&display=swap" rel="stylesheet"> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap" rel="stylesheet"> <title>Home</title> </head> <body> <section id="container"> <div id="main-flex-container"> <h1>Generate a <br><span>random password</span></h1> <h2>Never use an insecure password again.</h2> </div> <div id="input-flex-container"> <input type="text" id="password" readonly> <img src="clipboard.png" alt="复制到剪贴板"> </div> </section> <script src="script.js"></script> </body> </html>
额外说明
box-sizing: border-box是为了保证输入框的width包含内边距,不会因为添加padding-right而变宽- 可以根据实际图标的大小,调整
right、width、height以及输入框的padding-right数值,让布局更协调 - 给图标添加
cursor: pointer能让用户直观知道这是可点击的交互元素
内容的提问来源于stack exchange,提问作者TheNickster
相关产品推荐
相关产品推荐

