如何在不同分辨率下将图片精准置于双色背景分界处?
解决方法
要让图片始终一半在红色区域、一半在黄色区域,核心是让图片的中心精准对齐背景的颜色分界点,避免用margin/padding这类依赖外部容器的定位方式。以下是具体修改步骤:
1. 修正背景渐变写法
简化渐变代码,确保颜色分界严格在70%宽度处,同时让背景铺满整个视口高度:
body { background: linear-gradient(to right, #801404 70%, #ffac0c 70%); min-height: 100vh; }
2. 调整main容器的定位上下文
将main设为相对定位,为图片容器的绝对定位提供基准,同时让内容垂直居中:
main { display: flex; align-items: center; min-height: calc(100vh - 80px); /* 减去header高度,保证内容区域高度适配 */ position: relative; }
3. 精准定位图片容器
删除.right的margin,改用绝对定位对齐背景分界点,再向左偏移自身宽度的一半,确保图片中心落在分界线上:
.right { position: absolute; left: 70%; /* 对齐背景颜色分界点 */ transform: translateX(-50%); /* 偏移自身宽度的50%,让图片中心和分界点重合 */ }
4. 调整左侧文本容器位置
移除.left的left:10%,改用左侧margin保持距离,同时设置层级确保文本不被图片遮挡:
.left { margin: 0 0 0 10%; z-index: 1; }
修改后的完整CSS
* { margin: 0; padding: 0; box-sizing: border-box; font-family: Montserrat; text-decoration: none; color: inherit; } body { background: linear-gradient(to right, #801404 70%, #ffac0c 70%); min-height: 100vh; } header { display: flex; justify-content: space-between; align-items: center; padding: 50px 10%; height: 80px; } .nav-links li { color: white; text-transform: uppercase; font-weight:700; display: inline-block; list-style: none; padding: 0 20px; font-size: 2rem; } .logo-name { display: inline-flex; } .logo { width: 40px; height: auto; margin: 0 20px; filter: invert(99%) sepia(8%) saturate(808%) hue-rotate(172deg) brightness(122%) contrast(100%); } .name { font-size: 3rem; font-weight: 700; color: white; line-height: 80px; } .btn { padding: 15px 20px; background-color: #801404; color: white; text-transform: uppercase; border: none; border-radius: 50px; font-weight: 700; } main { display: flex; align-items: center; min-height: calc(100vh - 80px); position: relative; } .left { margin: 0 0 0 10%; z-index: 1; } .right { position: absolute; left: 70%; transform: translateX(-50%); } .left-title { font-size: 8rem; color: white; } .left-description{ font-size: 3rem; color: white; } .burgerimg { width: 400px; }
修改完成后,无论窗口如何缩放,图片都会始终保持一半在红色区域、一半在黄色区域,不会出现偏移。
内容的提问来源于stack exchange,提问作者flick9000
相关产品推荐
相关产品推荐

