如何让表格背景图片相对表格居中而非窗口?
让表格背景图片始终相对自身居中的解决方法
问题根源在于你给表格设置了background-attachment: fixed,这个属性会强制背景图片相对于浏览器视口固定定位,而非依附于表格元素本身,所以窗口尺寸变化时,图片位置会随视口变动,无法保持在表格中心。
修改方案
只需移除background-attachment: fixed这一行代码即可,其他背景属性可保留。修改后的完整代码如下:
<head> <style> table { background-image: url('./elements/pent.png'); background-size: 100px, 100px; background-repeat: no-repeat; /* 移除background-attachment: fixed */ background-color: rgba(255, 255, 255, 0.7); background-blend-mode: overlay; background-position: center center; border: 1px solid #b3adad; border-collapse: collapse; padding: 5px; } table th { border: 1px solid #b3adad; padding: 5px; color: #313030; } table td { border: 1px solid #b3adad; text-align: center; padding: 5px; color: #313030; } </style> </head> <body> <table style="white-space:nowrap"> <thead> <tr> <th><br></th> <th>Header1</th> <th>Header2</th> </tr> </thead> <tbody> <tr> <td>Row<br></td> <td>1</td> <td>0.52</td> </tr> <tr> <td>Row</td> <td>1</td> <td>0.52</td> </tr> <tr> <td>Row</td> <td>1</td> <td>0.52</td> </tr> <tr> <td>Row</td> <td>1</td> <td>0.52</td> </tr> <tr> <td>Row</td> <td>1</td> <td>0.52</td> </tr> <tr> <td>Row</td> <td>1</td> <td>0.52</td> </tr> <tr> <td>Row</td> <td>150</td> <td></td> </tr> </tbody> </table> </body> </html>
原理说明
- 当
background-attachment使用默认值(scroll)时,背景图片会绑定到表格元素的坐标系,background-position: center center会以表格的宽高中心为基准定位图片。 - 无论窗口如何缩放或滚动,图片都会始终保持在表格的中心位置,不会脱离表格。
内容的提问来源于stack exchange,提问作者Moses Kim
相关产品推荐
相关产品推荐

