如何让绝对定位按钮始终居中于自适应图片?
解决按钮始终居中于图片的问题
问题原因
你当前的代码里,按钮只设置了top: 50%,但这只是让按钮的顶部边缘对齐容器的垂直中线,没有将按钮自身向上偏移一半高度;同时水平方向用了right:10px固定右侧距离,不是真正的居中,所以窗口缩放后位置就偏了。
方案一:绝对定位 + transform(推荐)
这是最通用的居中方案,不管按钮自身尺寸如何变化,都能精准居中。修改.middle-key的CSS:
#full_image { position: relative; display: inline-block; max-width: 100%; } #full_image img { max-width: 100%; } #full_image .middle-key{ background-color:yellow; cursor: pointer; height: 29px; opacity: 1; position: absolute; width: 59px; z-index: 999; color: #222; text-decoration: none; text-align: center; line-height: 28px; /* 核心修改 */ top: 50%; left: 50%; transform: translate(-50%, -50%); }
原理:
top:50%和left:50%让按钮的左上角对齐容器的中心transform: translate(-50%, -50%)让按钮向左、向上各偏移自身尺寸的50%,最终整体居中
方案二:Flex布局
给父容器启用flex布局,直接利用flex的居中属性:
#full_image { position: relative; display: inline-flex; /* 改成inline-flex */ max-width: 100%; justify-content: center; /* 水平居中 */ align-items: center; /* 垂直居中 */ } #full_image img { max-width: 100%; } #full_image .middle-key{ background-color:yellow; cursor: pointer; height: 29px; opacity: 1; position: absolute; width: 59px; z-index: 999; color: #222; text-decoration: none; text-align: center; line-height: 28px; }
原理:
父容器的justify-content: center和align-items: center会让所有子元素(包括图片和按钮)居中,按钮用绝对定位不会占据布局空间,始终浮在图片中央。
两种方案都能实现你要的效果,窗口缩放、图片尺寸变化时按钮都会保持在图片中央。
内容的提问来源于stack exchange,提问作者4seasonn
相关产品推荐
相关产品推荐

