如何使两个div悬浮于图片上方?右侧div浮动失效求助
问题原因及解决方案
你遇到的问题很典型——当元素设置了position: absolute后,float属性会完全失效。这是因为绝对定位的元素已经脱离了正常的文档流,而float是专门针对文档流内的元素设计的布局属性,对脱离文档流的元素不起作用。
修复方案:用绝对定位的right属性替代float
既然你的.move元素已经是绝对定位,直接利用绝对定位的方位属性来控制位置就好,比如给.next类添加right属性:
修改后的完整CSS代码:
#newsline { position: relative; padding-top: 60px; transition: 0.5s; width: 100%; height: 400px; overflow: hidden; } #newsline a img { position: absolute; transition: 1s; height: 360px; width: 90%; margin: 20px 5% 20px 5%; } .move { z-index: 1; width: 100px; height: 100px; display: table; position: absolute; border-radius: 50px; margin-top: 150px; cursor: pointer; background-color: rgb(255, 255, 255, 0.25); } .move:hover { background-color: rgb(255, 255, 255, 0.6); } .move p { height: 100%; text-align: center; vertical-align: middle; display: table-cell; color: rgb(250, 255, 255, 0.7); font-size: 250%; background-color: transparent; /* 修正:CSS中background-color没有none值,用transparent表示透明 */ } .move p:hover { color: darkslategrey; } .next { /* 移除无效的float:right */ right: 6%; /* 和左侧按钮的margin-left:6%保持对称布局 */ } .previous { margin-left: 6%; }
原理说明
因为父容器#newsline设置了position: relative,所以绝对定位的.move元素会相对于父容器进行定位。用right: 6%可以直接让右侧按钮距离父容器右边缘6%的位置,和左侧按钮的margin-left:6%形成对称布局,效果比用float更精准可控。
内容的提问来源于stack exchange,提问作者MaestroD
相关产品推荐
相关产品推荐

