如何使图片始终居中于30%/70%宽度分割的div分界处?
问题:图片无法在窗口缩放时保持在div分割线居中
我尝试使用百分比定位,但窗口缩小时,图片无法保持在两个div的宽度分割线处水平居中。
左侧div占30%宽度,右侧div占剩余70%宽度。
我猜测可能需要手动调整位置百分比,但想知道是否存在适用于任意图片的实现方法?或如何调整现有代码实现该效果?
我的代码
HTML
<body> <header> <div class="indexHeaderWall" id="headerLeftWall"> </div> <img id="profilePic" src="icons/myPicture.jpg" alt="Picture of Daniel Campos"> <div class="indexHeaderWall" id="headerRightWall"> </div> </header> </body>
CSS
body { background-color: aqua; margin: 0%; } header { background-color: orange; display: flex; position: relative; } #profilePic { position: absolute; left: 26%; top: 0%; bottom: 0%; margin: auto 0%; } .indexHeaderWall { background-color: aliceblue; height: 300px; border: solid red 1px; } #headerLeftWall {width: 30%;} #headerRightWall {width: 70%;}
解决方案
你当前用固定left:26%的问题在于没有考虑图片自身宽度,窗口缩放时自然会偏移。要让图片始终居中在30%宽度的分割线(左侧div的右边缘),且适配任意图片宽度,只需要修改图片的CSS定位:
#profilePic { position: absolute; left: 30%; /* 对齐左侧div的右边缘 */ top: 0; bottom: 0; margin: auto 0; transform: translateX(-50%); /* 向左偏移自身宽度的50%,让图片中心落在分割线上 */ }
原理:
left:30%让图片的左边缘对齐左侧div的右边缘(也就是30%宽度的位置)transform: translateX(-50%)将图片向左移动自身宽度的一半,这样图片的中心点就刚好卡在分割线上,无论图片宽度多少、窗口怎么缩放都不会偏移。
如果你的需求是让图片的左边缘贴在分割线上,只需要去掉transform: translateX(-50%)即可。
另外,当前代码里的top:0; bottom:0; margin:auto 0已经能实现图片在header内的垂直居中,不需要额外调整。
内容的提问来源于stack exchange,提问作者Daniel Campos
相关产品推荐
相关产品推荐

